การใช้ LIKE operator เพื่อดึงข้อมูลหลายแถวที่ตรงรูปแบบ
LIKE ใช้สำหรับ pattern matching ใน WHERE clause โดยใช้ wildcard: % (ตัวอักษรใดๆ 0 ตัวขึ้นไป) และ _ (ตัวอักษรใดๆ 1 ตัว)
สร้างตารางและข้อมูล
mysql> create table DemoTable1385 (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Name varchar(20)
-> );
Query OK, 0 rows affected (0.90 sec)
mysql> insert into DemoTable1385(Name) values('Chris Brown');
mysql> insert into DemoTable1385(Name) values('Adam Smith');
mysql> insert into DemoTable1385(Name) values('Carol Taylor');
mysql> insert into DemoTable1385(Name) values('John Doe');
mysql> insert into DemoTable1385(Name) values('John Smith');
ข้อมูลทั้งหมด
+----+--------------+ | Id | Name | +----+--------------+ | 1 | Chris Brown | | 2 | Adam Smith | | 3 | Carol Taylor | | 4 | John Doe | | 5 | John Smith | +----+--------------+
คำสั่ง LIKE หานามสกุล Smith
mysql> select * from DemoTable1385 where Name LIKE '%Smith';
ผลลัพธ์
+----+------------+ | Id | Name | +----+------------+ | 2 | Adam Smith | | 5 | John Smith | +----+------------+
Wildcard Patterns พื้นฐาน
| Pattern | ความหมาย | ตัวอย่างตรง |
|---|---|---|
%Smith | ลงท้ายด้วย Smith | Adam Smith, John Smith |
John% | ขึ้นต้นด้วย John | John Doe, John Smith |
%John% | มี John อยู่ตรงไหนก็ได้ | John Doe, John Smith |
_ohn | 4 ตัวอักษร ตัวสุดท้าย 3 ตัวคือ ohn | John |
J__n | 4 ตัวอักษร เริ่ม J จบ n | John, Joan |
Case Sensitivity
- Collation ค่าเริ่มต้น (เช่น
utf8_general_ci) = Case-insensitive - ใช้
COLLATE utf8_binหรือBINARYสำหรับ case-sensitive:WHERE Name LIKE '%smith' COLLATE utf8_bin
ประสิทธิภาพและ Index
LIKE 'prefix%'(prefix wildcard) — ใช้ index ได้LIKE '%suffix'หรือLIKE '%middle%'— ไม่ใช้ index (Full table scan)- สำหรับ full-text search จริง ใช้
FULLTEXT INDEXและMATCH() AGAINST()
ข้อแนะนำ: หลีกเลี่ยง leading wildcard (%...) บนตารางใหญ่ ควรพิจารณา Full-text search หรือเก็บข้อมูลในรูปแบบที่ค้นหาได้ง่ายกว่า (เช่น แยก first/last name)