การใช้งาน LIKE สำหรับการค้นหาบางส่วน
ตัวดำเนินการ LIKE ช่วยให้ค้นหาข้อมูลที่ตรงกับรูปแบบ (Pattern) ได้ โดยใช้ตัวแทน (Wildcard):
%- แทนลำดับตัวอักษรใดๆ (0 ตัวขึ้นไป)_- แทนตัวอักษรเพียง 1 ตัว
ตัวอย่าง: ค้นหาวิชาที่มีคำว่า "Depth"
mysql> create table DemoTable806(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(100),
StudentSubject varchar(100) );
Query OK, 0 rows affected (0.57 sec)
mysql> insert into DemoTable806(StudentName,StudentSubject) values('Chris','Java in Depth With Data Structure');
mysql> insert into DemoTable806(StudentName,StudentSubject) values('Robert','Introduction to MySQL');
mysql> insert into DemoTable806(StudentName,StudentSubject) values('Bob','C++ in Depth With Data Structure And Algorithm');
mysql> insert into DemoTable806(StudentName,StudentSubject) values('Adam','Introduction to MongoDB');
ค้นหาด้วย LIKE '%Depth%'
mysql> select * from DemoTable806 where StudentSubject LIKE '%Depth%';
ผลลัพธ์:
+-----------+-------------+------------------------------------------------+
| StudentId | StudentName | StudentSubject |
+-----------+-------------+------------------------------------------------+
| 1 | Chris | Java in Depth With Data Structure |
| 3 | Bob | C++ in Depth With Data Structure And Algorithm |
+-----------+-------------+------------------------------------------------+
รูปแบบ LIKE ที่นิยมใช้
| รูปแบบ | ความหมาย | ตัวอย่าง |
|---|---|---|
%text% | มี text อยู่ที่ไหนก็ได้ | %Depth% |
text% | ขึ้นต้นด้วย text | Java% |
%text | ลงท้ายด้วย text | %Structure |
_ext | ตัวอักษรแรกอะไรก็ได้ ตามด้วย ext | _epth |
สรุป
LIKE เป็นเครื่องมือสำคัญสำหรับการค้นหาข้อความบางส่วน ใช้ % สำหรับการจับคู่แบบยืดหยุ่น และควรสร้าง Index แบบ Fulltext สำหรับตารางขนาดใหญ่