如何在 MySQL LIKE 子句中使用用户变量?
我们可以使用 CONCAT() 函数在 LIKE 子句中使用用户变量。语法如下。
set @anyVariableName='anyValue';
select yourColumnName1,yourColumnName2,yourColumnName3,...N from yourTableName
whereyourColumnName like CONCAT('%', @anyVariableName, '%');要理解上述语法,我们首先创建一个表。创建表所需的查询如下。
mysql> create table UserVariableInLike -> ( -> id int, -> Name varchar(100), -> Age int -> ); Query OK, 0 rows affected (0.83 sec)
使用 insert 命令在表中插入记录。查询如下所示。
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)
使用 select 语句显示表中的所有记录。查询如下
mysql> select *from UserVariableInLike;
以下是输出。
+------+-------------+------+ | 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)
以下是使用 LIKE 子句中的用户变量的查询。查询如下−
mysql> set @searchName='John';
Query OK, 0 rows affected (0.00 sec)
mysql> select id,Name,Age from UserVariableInLike where Name like CONCAT('%',
@searchName, '%');以下是输出。
+------+------------+------+ | id | Name | Age | +------+------------+------+ | 101 | John | 23 | | 102 | JohnSmith | 24 | | 104 | Johnson | 25 | +------+------------+------+ 3 rows in set (0.05 sec)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP