Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

MySQL tìm kiếm văn bản với LIKE và OR để lấy bản ghi

Ví dụ

Tìm các chủ đề (Subject) chứa từ "MySQL" HOẶC chứa từ "using".

1. Tạo bảng

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

2. Chèn dữ liệu

mysql> insert into DemoTable values('Introduction to MySQL');
mysql> insert into DemoTable values('Deep Dive using Java');
mysql> insert into DemoTable values('C in Depth');
mysql> insert into DemoTable values('Introduction to C++');

3. Xem dữ liệu

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)

4. Truy vấn LIKE với OR

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

Kết quả:

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

Mẹo: % là ký tự đại diện cho chuỗi bất kỳ độ dài. LIKE không phân biệt chữ hoa/thường theo collation mặc định.