如何在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 祝福语女友文案简短霸气