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 的情况,这是为了防止后面的
注:where 1=1 ,后面的条件也会走索引,不影响查询效率,我们写的sql指令会被mysql 进行解析优化成自己的处理指令,在这个过程中1 = 1这类无意义的条件将会被优化。使用explain EXTENDED sql 进行校对,发现确实where1=1这类条件会被mysql的优化器所优化掉。
但是,我们在mybatis当中可以改变一下写法,因为毕竟mysql优化器也是需要时间的,虽然是走了索引,但是当数据量很大时,还是会有影响的,所以我们建议代码修改如下:
二、
<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>
使用