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

MySQL: ใช้ LIKE Clause สองครั้งใน Query เดียว

สร้างตารางและข้อมูลตัวอย่าง

mysql> create table DemoTable2009 ( Name varchar(20) );
mysql> insert into DemoTable2009 values('John Doe');
mysql> insert into DemoTable2009 values('Adam Smith');
mysql> insert into DemoTable2009 values('John Smith');
mysql> insert into DemoTable2009 values('David Miller');

ข้อมูลในตาราง

+--------------+
| Name         |
+--------------+
| John Doe     |
| Adam Smith   |
| John Smith   |
| David Miller |
+--------------+

Query ใช้ LIKE 2 ครั้ง (OR)

mysql> select * from DemoTable2009 where Name like '%Smith%' or Name like '%David%';

ผลลัพธ์

+--------------+
| Name         |
+--------------+
| Adam Smith   |
| John Smith   |
| David Miller |
+--------------+

อธิบาย

  • Name LIKE '%Smith%' → ตรงกับ "Adam Smith", "John Smith"
  • Name LIKE '%David%' → ตรงกับ "David Miller"
  • OR รวมเงื่อนไขทั้งสอง (Union Logic)

รูปแบบอื่นที่เทียบเท่า

-- ใช้ REGEXP (Regular Expression)
SELECT * FROM DemoTable2009 WHERE Name REGEXP 'Smith|David';

-- ใช้ IN กับ Subquery (สำหรับรายการเยอะ)
SELECT * FROM DemoTable2009 WHERE Name IN (
    SELECT Name FROM DemoTable2009 WHERE Name LIKE '%Smith%' OR Name LIKE '%David%'
);

Performance Tip

  • LIKE '%text%' (Leading Wildcard) → Full Table Scan ไม่ใช้ Index ได้
  • หากค้นหาบ่อย ควรใช้ Full-Text Search (MATCH...AGAINST) หรือ Search Engine เช่น Elasticsearch/Sphinx
  • LIKE 'text%' (Trailing Wildcard Only) → ใช้ Index ได้

กรณี AND (ทั้งสองเงื่อนไขต้องตรงพร้อมกัน)

SELECT * FROM DemoTable2009 WHERE Name LIKE '%John%' AND Name LIKE '%Smith%';

จะได้แค่ "John Smith" เท่านั้น