如何在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 -> );
使用insert命令在表中插入记录。查询如下。
mysql> insert into UserVariableInLike values(101,'John',23); mysql> insert into UserVariableInLike values(102,'John Smith',24); mysql> insert into UserVariableInLike values(103,'Carol Smith',23); mysql> insert into UserVariableInLike values(104,'Johnson',25); mysql> insert into UserVariableInLike values(105,'Adam Smith',26);
使用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';
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)
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短