Search สตริงในคอลัมน์ TEXT/ VARCHAR ด้วย LIKE
ใช้ Wildcard % (ทุกความยาว) และ _ (ตัวอักษรเดี่ยว) ร่วมกับ LIKE
รูปแบบคำสั่ง (Syntax)
SELECT * FROM yourTableName
WHERE yourColumnName LIKE '%search_string%';
Wildcard Patterns
| Pattern | ความหมาย | ตัวอย่าง Match |
|---|---|---|
%text% | มี text อยู่กลาง/หน้า/หลัง | "text", "my text", "text here" |
text% | ขึ้นต้นด้วย text | "text", "textbook" |
%text | ลงท้ายด้วย text | "text", "context" |
_ext | ตัวอักษรตัวแรกอะไรก็ได้ ตามด้วย ext | "text", "next" |
%text_ | มี text แล้วตามด้วย 1 ตัวอักษร | "texts", "text1" |
ตัวอย่างการใช้งาน
สร้างตาราง SearchTextDemo:
CREATE TABLE SearchTextDemo (
BookName TEXT
);
ข้อมูลหนังสือ:
| BookName |
|---|
| Let us C |
| C in Depth |
| C in Depth with Data Structure |
| Introduction to Java |
| Java in Depth |
ค้นหา "in Depth":
SELECT * FROM SearchTextDemo
WHERE BookName LIKE '%in Depth%';
ผลลัพธ์:
| BookName |
|---|
| C in Depth |
| C in Depth with Data Structure |
| Java in Depth |
ประสิทธิภาพและทางเลือก
LIKE '%text%'(Leading wildcard) → Full Table Scan ช้าLIKE 'text%'(Trailing wildcard only) → ใช้ Index ได้ เร็ว- ข้อมูลเยอะ/ค้นหาบ่อย → ใช้ Full-Text Search (
MATCH() AGAINST()) - MySQL 8.0+ → ใช้
REGEXPสำหรับ Pattern ซับซ้อน