一个模糊查询条件问题
两个条件,当第二个条件没有值;
-- 会查询所有sex=1,后面的模糊查询失效,匹配所有(因为为空串) select * from tb_user where sex = 1 and name like '%%' ; -- 查询不到任何结果 select * from tb_user where sex = 1 and name like '% %'; -- 查询不到任何结果 select * from tb_user where sex = 1 and name like '%null%'
当没值时不作为查询条件,而不是查null/空串
<select id="queryMaleUserByUserName" parameterType="User" resultType="User"> select * from tb_user where sex = 1 <if test="userName!=null and userName!=''"> and user_name like "%"#{userName}"%" </if> </select>
使用双引号,或使用单引号并且空格,正确
select * from tb_user where sex = 1 and user_name like '%' #{userName} '%' 传入参数后的效果 select * from tb_user where name like '%' '张' '%' (其实是一种拼接的形式了) 以上,使用单引号要有空格 ,如果是双引号则不用,"%"#{userName}"%" ,#{}在传参后给参数拼接上引号,拼的是单引号
使用单引号,没有空格的情况下下,错误
select * from tb_user where sex = 1 and user_name like '%'#{userName}'%' 传入参数的效果,被当做'?整体去查找,查的是'?',根本没这玩意 select * from tb_user where name like '%''张''%'