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

Truy vấn LIKE với mảng động trong MySQL

Sử dụng LIKE với ký tự đại diện. Cú pháp:

SELECT * FROM tenBang
WHERE tenCot LIKE '%giaTri%'
ORDER BY tenCotKhac ASC
LIMIT giaTriGioiHan;

Tạo bảng demo74:

mysql> CREATE TABLE demo74 (
    -> user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> user_names VARCHAR(250)
    -> );

Chèn dữ liệu (cột user_names chứa nhiều tên phân cách bằng dấu phẩy):

mysql> INSERT INTO demo74(user_names) VALUES('John Smith1,John Smith2,John Smith3');
mysql> INSERT INTO demo74(user_names) VALUES('John Smith1');
mysql> INSERT INTO demo74(user_names) VALUES('David Smith1');
mysql> INSERT INTO demo74(user_names) VALUES('John Smith1,John Smith2,John Smith3,John Smith4');

Hiển thị dữ liệu:

mysql> SELECT * FROM demo74;
+---------+-------------------------------------------------+
| user_id | user_names                                      |
+---------+-------------------------------------------------+
| 1       | John Smith1,John Smith2,John Smith3             |
| 2       | John Smith1                                     |
| 3       | David Smith1                                    |
| 4       | John Smith1,John Smith2,John Smith3,John Smith4 |
+---------+-------------------------------------------------+

Truy vấn tìm các hàng chứa 'John Smith1':

mysql> SELECT * FROM demo74
    -> WHERE user_names LIKE '%John Smith1%'
    -> ORDER BY user_id ASC
    -> LIMIT 100;

Kết quả:

+---------+-------------------------------------------------+
| user_id | user_names                                      |
+---------+-------------------------------------------------+
| 1       | John Smith1,John Smith2,John Smith3             |
| 2       | John Smith1                                     |
| 4       | John Smith1,John Smith2,John Smith3,John Smith4 |
+---------+-------------------------------------------------+