เมื่อต้องการค้นหาข้อมูลที่ขึ้นต้นด้วยตัวอักษรหรือสตริงเฉพาะ ให้ใช้ Operator LIKE พร้อม Wildcard % ต่อท้าย Pattern
สร้างตารางและข้อมูล
mysql> create table DemoTable (StudentFirstName varchar(20));
mysql> insert into DemoTable values('John'),('Carol'),('Johnny'),('Robert'),('Chris'),('Ramit');
ข้อมูลในตาราง
+------------------+ | StudentFirstName | +------------------+ | John | | Carol | | Johnny | | Robert | | Chris | | Ramit | +------------------+
ค้นหาชื่อขึ้นต้นด้วย 'C'
mysql> select * from DemoTable where StudentFirstName LIKE 'C%';
ผลลัพธ์
+------------------+ | StudentFirstName | +------------------+ | Carol | | Chris | +------------------+
Pattern LIKE พื้นฐาน
| Pattern | ความหมาย | Match |
|---|---|---|
'C%' | ขึ้นต้น C | Carol, Chris, Cat |
'%C' | ลงท้าย C | Marc, Lucas |
'%C%' | มี C อยู่ไหนก็ได้ | Carol, Alice, Bob |
'C_' | ขึ้นต้น C ความยาว 2 ตัว | Ca, Ce (ไม่ใช่ Carol) |
'C__%' | ขึ้นต้น C ความยาวอย่างน้อย 3 | Car, Cat, Carol |
Case Sensitivity
- Default Collation (utf8mb4_general_ci, utf8_unicode_ci) → Case Insensitive
- 'C%' จะ Match 'carol', 'CAROL', 'Carol' ทั้งหมด
- ต้องการ Case Sensitive:
WHERE StudentFirstName LIKE BINARY 'C%'หรือ Collation_cs(Case Sensitive) หรือ_bin(Binary)
ประสิทธิภาพและ Index
LIKE 'prefix%'- ใช้ Index ได้ (Range Scan)LIKE '%suffix'- ไม่ใช้ Index (Full Scan)LIKE '%middle%'- ไม่ใช้ Index
Optimization: Prefix Index
-- สร้าง Index เฉพาะ 10 ตัวอักษรแรก CREATE INDEX idx_name_prefix ON DemoTable(StudentFirstName(10));
MySQL 8.0+ Functional Index
CREATE INDEX idx_name_lower ON DemoTable((LOWER(StudentFirstName)));