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

ค้นหาข้อมูลตรงกับข้อความใดข้อความหนึ่งใน MySQL ด้วย LIKE OR

บทความนี้สาธิตการค้นหาแถวที่คอลัมน์ Title มีคำใดคำหนึ่งจากหลายคำ (MySQL หรือ Algorithm) โดยใช้ LIKE ... OR LIKE ...

สร้างตารางและข้อมูลบทความ

mysql> CREATE TABLE DemoTable762 (Title TEXT);
Query OK, 0 rows affected (0.54 sec)

mysql> INSERT INTO DemoTable762 VALUES('Introduction to Java');
mysql> INSERT INTO DemoTable762 VALUES('MySQL is a RDBMS');
mysql> INSERT INTO DemoTable762 VALUES('Data Structure and Algorithm in Java');
mysql> INSERT INTO DemoTable762 VALUES('Data Structure and Algorithm in C and C++');

คิวรีค้นหา 'MySQL' หรือ 'Algorithm'

mysql> SELECT * FROM DemoTable762 
WHERE Title LIKE '%MySQL%' OR Title LIKE '%Algorithm%';

ผลลัพธ์ (3 จาก 4 แถว)

+-------------------------------------------+
| Title                                     |
+-------------------------------------------+
| MySQL is a RDBMS                          |
| Data Structure and Algorithm in Java      |
| Data Structure and Algorithm in C and C++ |
+-------------------------------------------+

คำอธิบาย:

  • LIKE '%MySQL%' - มีคำว่า MySQL อยู่ตรงไหนก็ได้
  • OR - ตัวดำเนินการ OR Logic (TRUE ถ้าตรงเงื่อนไขไหนเงื่อนไขหนึ่ง)
  • LIKE '%Algorithm%' - มีคำว่า Algorithm อยู่ตรงไหนก็ได้
  • แถว 'Introduction to Java' ไม่มีคำใดคำหนึ่ง → ถูกตัดออก

ทางเลือก (Regex): WHERE Title REGEXP '(MySQL|Algorithm)' (ดูบทความ ID 1004074320)

ประสิทธิภาพ: Leading Wildcard (%...) ทำ Full Table Scan → ใช้ Full-Text Search สำหรับข้อมูลเยอะ