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 > 标签会产生问题:

  1. 如果if都不成立,会变成:

    SELECT * FROM BLOG	WHERE
    

    该语句会出错

  2. 如果第一条if不成立,第2条/第3条成立

    SELECT * FROM BLOG	WHERE AND title like xxx
    

    多出现一个AND该语句也会出错

解决方案:

SELECT * FROM BLOG WHERE 1=1 加上<if>标签
  1. 使用标签,下面介绍

2.< where > 标签+< if > 标签

Mybatis为了解决上面的问题,给了< where >标签 ,直接解决了上面的两个问题

  1. 当全部不匹配的时候 where 不会出现在sql语句中

  2. 当第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>
posted @ 2022-12-08 14:20  yikolemon  阅读(188)  评论(0)    收藏  举报