Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ปรับปรุงประสิทธิภาพการค้นหา MySQL ด้วย Wildcards (%%)


ไม่สามารถปรับปรุงได้ หากใช้ Leading Wildcard (%text) เพราะ MySQL จะไม่สามารถใช้ Index ได้ การค้นหาจะทำ Full Table Scan

แต่ถ้าใช้ Trailing Wildcard (text%) MySQL จะใช้ Index ได้ ทำให้ค้นหาเร็วขึ้นมาก

รูปแบบที่แนะนำ (Trailing Wildcard)

SELECT * FROM yourTableName WHERE yourColumnName LIKE 'anyLetter%';

ตัวอย่างการใช้งาน

สร้างตารางและเพิ่มข้อมูลชื่อ:

mysql> CREATE TABLE TrailingWildCardDemo ( Id INT NOT NULL AUTO_INCREMENT, Name VARCHAR(20), PRIMARY KEY(Id) ); 
INSERT INTO TrailingWildCardDemo(Name) VALUES('John'),('Johnson'),('Mike'),('Kevin'),('Adam'),('Ethan'),('James');

ค้นหาชื่อขึ้นต้นด้วย J (Trailing wildcard):

mysql> SELECT * FROM TrailingWildCardDemo WHERE Name LIKE 'j%';

ผลลัพธ์ (ใช้ Index ได้):

+----+---------+ | Id | Name    | +----+---------+ | 1  | John    | | 2  | Johnson | | 7  | James   | +----+---------+ 3 rows in set (0.00 sec)

สรุป: หลีกเลี่ยง %text (Leading wildcard) ใช้ text% (Trailing wildcard) แทนเพื่อให้ Index ทำงาน