Giới thiệu
Toán tử LIKE trong MySQL so khớp mẫu (pattern) cho phép tìm chuỗi con bất kể dấu câu xung quanh, vì % khớp với bất kỳ chuỗi nào (kể cả rỗng, dấu câu, khoảng trắng).
1. Tạo bảng và dữ liệu
mysql> create table DemoTable (
-> Comments varchar(20)
-> );
Query OK, 0 rows affected (1.10 sec)
mysql> insert into DemoTable values('Good,Morning');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Nice');
Query OK, 1 row affected (0.51 sec)
mysql> insert into DemoTable values('good,bye!');
Query OK, 1 row affected (0.11 sec)
2. Dữ liệu gốc
mysql> select *from DemoTable;
+--------------+ | Comments | +--------------+ | Good,Morning | | Nice | | good,bye! | +--------------+ 3 rows in set (0.00 sec)
3. Tìm từ "good" (bỏ qua hoa/thường, dấu câu)
mysql> select *from DemoTable where Comments like '%good%';
4. Kết quả
+--------------+ | Comments | +--------------+ | Good,Morning | | good,bye! | +--------------+ 2 rows in set (0.00 sec)
Giải thích:
%good%khớp: "Good,Morning" (chữ G hoa, có dấu phẩy), "good,bye!" (thường, có dấu phẩy, chấm than)- MySQL
LIKEmặc định không phân biệt chữ hoa/thường (case-insensitive) cho charset mặc định (utf8mb4_general_ci) - Dấu phẩy, chấm than được coi là ký tự thường, bị
%"nuốt" hết
Nếu cần phân biệt chữ hoa/thường:
WHERE Comments LIKE '%good%' COLLATE utf8mb4_bin -- hoặc WHERE BINARY Comments LIKE '%good%'
Tìm kiếm toàn văn bản (Full-text) tốt hơn cho văn bản dài: Sử dụng MATCH() AGAINST() với FULLTEXT index (xem bài 1003075114, 1003075135).