mysql中in条件使用字符串
场景
当sql使用in作为条件时,使用一个参数满足查询条件,直接传入字符串无法满足条件。
select id,name from user where id in(?)
方法
使用find_in_set(str,strlist)函数
select id,name from user where find_in_set(id,#{strlist})
str
: 条件字段strlist
:匹配值集合
select id,name from user where find_in_set(id,'111,22,333')
mysql查询 in条件参数为带逗号的字符串,查询结果错误
如有以下sql:
select ( select group_concat(content) from account_limit_user ur where ur.id in (t1.limit_user) group by ur.id ) as limit_user from account t1 where 1 = 1
t1.limit_user 为account表中查询出来的值
‘9,8,4’
查询sql正确查询结果应为:
不可推荐 ,推销客户,推销客户
实际结果为:
不可推荐
原因:
在mysql中in里面如果是字符串的话,会自动转化成int类型的,内部使用了如下方法:
cast('4,3' as int)
导致’4,3‘ 变成了4,所以上述查询sql结果只有第一个。
解决方案
find_in_set('查询的值(如:1)', '使用逗号隔开的字符串集合,如:('1,2,3')')
正确的sql
select ( select group_concat(content) from account_limit_user ur where find_in_set(ur.id, t1.limit_user) > 0 ) as limit_user, t1.limit_user limit_userid from account t1 where 1 = 1
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。