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

การค้นหาข้อความด้วย LIKE และ OR ใน MySQL

ใช้ LIKE ร่วมกับ OR เพื่อค้นหาข้อความที่ตรงกับเงื่อนไขใดเงื่อนไขหนึ่ง

สร้างตารางตัวอย่าง

mysql> create table DemoTable ( 
    Subject text ); 
Query OK, 0 rows affected (0.86 sec)

เพิ่มข้อมูลตัวอย่าง

mysql> insert into DemoTable values('Introduction to MySQL'); Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable values('Deep Dive using Java'); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('C in Depth'); Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Introduction to C++'); Query OK, 1 row affected (0.48 sec)

แสดงข้อมูลทั้งหมด

mysql> select *from DemoTable;
+-----------------------+
| Subject               |
+-----------------------+
| Introduction to MySQL |
| Deep Dive using Java  |
| C in Depth            |
| Introduction to C++   |
+-----------------------+
4 rows in set (0.00 sec)

คิวรี่ค้นหาที่มี "MySQL" หรือ "using"

mysql> select *from DemoTable where Subject LIKE '%MySQL%' OR Subject LIKE '%using%';

ผลลัพธ์:

+-----------------------+
| Subject               |
+-----------------------+
| Introduction to MySQL |
| Deep Dive using Java  |
+-----------------------+
2 rows in set (0.00 sec)

คำอธิบาย LIKE Pattern

  • % - ตรงกับตัวอักษร 0 หรือมาก ตัว
  • _ - ตรงกับตัวอักษร 1 ตัว อย่างแน่นอน
  • '%MySQL%' - มีคำว่า MySQL อยู่ที่ไหนก็ได้
  • 'MySQL%' - เริ่มต้นด้วย MySQL
  • '%MySQL' - จบด้วย MySQL

Case Sensitivity

  • ขึ้นกับ Collation: _ci (Case Insensitive) = default, _cs (Case Sensitive), _bin (Binary)
  • บังคับ Case Sensitive: WHERE Subject COLLATE utf8mb4_bin LIKE '%MySQL%'

ประสิทธิภาพและ Full-Text Search

  • LIKE '%keyword%' (Leading wildcard) → Full Table Scan ไม่ใช้ Index
  • LIKE 'keyword%' (Trailing wildcard only) → ใช้ Index ได้
  • สำหรับข้อความยาว/ข้อมูลเยอะ ใช้ Full-Text Search:
    ALTER TABLE DemoTable ADD FULLTEXT(Subject);
    SELECT * FROM DemoTable WHERE MATCH(Subject) AGAINST('MySQL');

Regular Expression (REGEXP)

WHERE Subject REGEXP 'MySQL|using'