Computer >> Máy Tính >  >> Lập trình >> MySQL

Cách sử dụng biến người dùng trong mệnh đề LIKE của MySQL?


Sử dụng hàm CONCAT (), chúng ta có thể làm việc với các biến người dùng trong mệnh đề LIKE. Cú pháp như sau.

set @anyVariableName='anyValue';
select yourColumnName1,yourColumnName2,yourColumnName3,...N from yourTableName
whereyourColumnName like CONCAT('%', @anyVariableName, '%');

Để hiểu cú pháp trên, trước tiên chúng ta hãy tạo một bảng. Truy vấn để tạo bảng như sau.

mysql> create table UserVariableInLike
-> (
-> id int,
-> Name varchar(100),
-> Age int
-> );
Query OK, 0 rows affected (0.83 sec)

Chèn bản ghi trong bảng bằng lệnh chèn. Truy vấn như sau.

mysql> insert into UserVariableInLike values(101,'John',23);
Query OK, 1 row affected (0.23 sec)

mysql> insert into UserVariableInLike values(102,'John Smith',24);
Query OK, 1 row affected (0.20 sec)

mysql> insert into UserVariableInLike values(103,'Carol Smith',23);
Query OK, 1 row affected (0.15 sec)

mysql> insert into UserVariableInLike values(104,'Johnson',25);
Query OK, 1 row affected (0.20 sec)

mysql> insert into UserVariableInLike values(105,'Adam Smith',26);
Query OK, 1 row affected (0.21 sec)

Hiển thị tất cả các bản ghi từ bảng bằng cách sử dụng câu lệnh select. Truy vấn như sau

mysql> select *from UserVariableInLike;

Sau đây là kết quả đầu ra.

+------+-------------+------+
| id   | Name        | Age  |
+------+-------------+------+
| 101  | John        | 23   |
| 102  | John Smith  | 24   |
| 103  | Carol Smith | 23   |
| 104  | Johnson     | 25   |
| 105  | Adam Smith  | 26   |
+------+-------------+------+
5 rows in set (0.00 sec)

Đây là truy vấn sử dụng biến người dùng trong mệnh đề LIKE. Truy vấn như sau -

mysql> set @searchName='John';
Query OK, 0 rows affected (0.00 sec)

mysql> select id,Name,Age from UserVariableInLike where Name like CONCAT('%',
@searchName, '%');

Sau đây là kết quả đầu ra.

+------+------------+------+
| id   | Name       | Age  |
+------+------------+------+
| 101  | John       | 23   |
| 102  | JohnSmith  | 24   |
| 104  | Johnson    | 25   |
+------+------------+------+
3 rows in set (0.05 sec)