如何在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 红包祝福语简短10字
18 周六早晨祝福语简短