Mybatis SQL语句的where和<where>区别

一、where子句

在平时写SQL语句的时候,经常会写为:

<select id="queryBookInfo" parameterType="com.ths.platform.entity.BookInfo" resultType="java.lang.Integer">
 select count(id) from t_book t where 1=1
   <if test="title !=null and title !='' "> AND title = #{title} </if> <if test="author !=null and author !='' "> AND author = #{author} </if> </select>

可以看到,SQL语句中,有 where 1=1 的情况,这是为了防止后面的 <if>语句都为空的情况。

注:where 1=1 ,后面的条件也会走索引,不影响查询效率,我们写的sql指令会被mysql 进行解析优化成自己的处理指令,在这个过程中1 = 1这类无意义的条件将会被优化。使用explain EXTENDED  sql 进行校对,发现确实where1=1这类条件会被mysql的优化器所优化掉。

但是,我们在mybatis当中可以改变一下写法,因为毕竟mysql优化器也是需要时间的,虽然是走了索引,但是当数据量很大时,还是会有影响的,所以我们建议代码修改如下:

 

二、<where>标签:

<select id="queryBookInfo" parameterType="com.ths.platform.entity.BookInfo" resultType="java.lang.Integer">
 select count(*) from t_book t
    <where>
        <if test="title !=null and title !='' ">
             title = #{title} 
        </if>
        <if test="author !=null and author !='' "> 
             AND author = #{author}
        </if>
    </where> 
</select>

使用<where>标签代替 where子句,<where>标签为Mybatis的动态语句,上述代码中若where标签里的if全都不成立,则不走where语句。若第一个 title值为null,则打印出来的 SQL语句为:select count(*) from t_book t where author = "xx",会把第一个AND/OR自动忽略掉若直接用where子句的话可能会导致sql语法错误,查询失败。

 

posted @ 2022-03-01 10:14  星海寻梦233  阅读(2433)  评论(0编辑  收藏  举报