Mysql中where if问题
网上关于Mybatis中where与if的说法乱七八糟的,Myabtis官网写的很清晰。为了防止误导他人,在此记录:
1.where语句+< if > 标签
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
直接写Where再使用< if > 标签会产生问题:
-
如果if都不成立,会变成:
SELECT * FROM BLOG WHERE该语句会出错
-
如果第一条if不成立,第2条/第3条成立
SELECT * FROM BLOG WHERE AND title like xxx多出现一个AND该语句也会出错
解决方案:
SELECT * FROM BLOG WHERE 1=1 加上<if>标签
- 使用
标签,下面介绍
2.< where > 标签+< if > 标签
Mybatis为了解决上面的问题,给了< where >标签 ,直接解决了上面的两个问题
-
当全部不匹配的时候 where 不会出现在sql语句中
-
当第1个不匹配的时候,后面第一个成立的语句会自动去掉最前的and
(注意,AND需要写在最前,如果写在最后还会出现问题)
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>

浙公网安备 33010602011771号