Truy vấn MySQL khớp bất kỳ chuỗi nào trong hai chuỗi từ giá trị cột
Để thực hiện việc này, bạn có thể sử dụng toán tử LIKE với điều kiện OR.
Hãy tạo một bảng trước:
mysql> create table DemoTable762 (Title text); Query OK, 0 rows affected (0.54 sec)
Chèn một số bản ghi vào bảng bằng lệnh insert:
mysql> insert into DemoTable762 values('Introduction to Java');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable762 values('MySQL is a RDBMS');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable762 values('Data Structure and Algorithm in Java');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable762 values('Data Structure and Algorithm in C and C++');
Query OK, 1 row affected (0.18 sec)
Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select:
mysql> select * from DemoTable762;
Điều này sẽ tạo ra đầu ra sau:
+-------------------------------------------+ | Title | +-------------------------------------------+ | Introduction to Java | | MySQL is a RDBMS | | Data Structure and Algorithm in Java | | Data Structure and Algorithm in C and C++ | +-------------------------------------------+ 4 rows in set (0.00 sec)
Truy vấn sau khớp bất kỳ chuỗi nào trong hai chuỗi "MySQL" hoặc "Algorithm":
mysql> select * from DemoTable762 where Title LIKE '%MySQL%' or Title LIKE '%Algorithm%';
Điều này sẽ tạo ra đầu ra sau:
+-------------------------------------------+ | Title | +-------------------------------------------+ | MySQL is a RDBMS | | Data Structure and Algorithm in Java | | Data Structure and Algorithm in C and C++ | +-------------------------------------------+ 3 rows in set (0.00 sec)
Phương án thay thế: Sử dụng REGEXP: WHERE Title REGEXP 'MySQL|Algorithm' gọn nhẹ hơn khi có nhiều từ khóa.