博主遇到的业务场景为,前端下拉多选,传给后端的查询条件为字符串数组,如[篮球,足球,排球,乒乓球],而数据库存的是逗号分隔的字符串,如:篮球,足球,排球,这个时候用模糊查询肯定是不行的,有经验的同学知道这时候可以用 FIND_IN_SET 去实现,但是怎么写呢?
如果只是sql查询的话,我们可以这样写
select* from you_table where 1=1 and find_in_set( '篮球', '篮球,足球,排球' )
如果是mybatis查询的话,我们可以使用下面的方式
<if test="params.productLine != null and params.productLine.size() > 0"> and ( <foreach item="value" index="index" collection="params.productLine" separator="OR"> <foreach item="subValue" index="subIndex" collection="value.split(',')"> FIND_IN_SET(#{subValue}, sp.product_line) </foreach> </foreach> ) </if>
需要注意的是需要对集合的长度做判断,同时在对集合循环是要在外面加and(),使得find_in_set语句整体作为一个条件,拼接在我们正常条件语句后面