mybatis where 1=1导致索引失效问题探究
在mybatis中常用到if标签判断where子句后的条件,为防止首字段为空导致sql报错,我之前 在where后加了1=1来处理该问题。
后来又用了mybatis的where标签,并自己做过测试,where标签会判断优化处理and/or开头的条件。所以直接解决了那个问题。
那么1=1方式有什么不好的呢。会导致索引失效吗?
其中id_card为唯一索引,所以命中了索引。再试试。
EXPLAIN SELECT * FROM USER WHERE 1=1 AND id_card='622772199303134433' AND age=20 ;
为了测试 sex+age设为联合唯一索引
EXPLAIN SELECT * FROM USER WHERE sex=1 AND age=20 ;
EXPLAIN SELECT * FROM `user` WHERE 1=1 AND sex=1 AND age=20 ;
依然命中了索引
那么1=1到底会不会让索引失效呢?
where 1=1不会影响性能。sql优化器已经处理过了。所以两种方式都可以。
<!-- 查询 不触发索引-->
<select id="findUser" resultType="com.cnzz.mybatis.PO.UserPO">
SELECT * FROM user WHERE 1=1
<if test="idCard !=null and idCard!=''">
and id_card=#{idCard}
</if>
<if test="name !=null and name!=''">
and `name`=#{name}
</if>
<if test="age !=null">
and age=#{age}
</if>
<if test="sex !=null">
and sex=#{sex}
</if>
;
</select>
<!-- 查询 首部字段为空,是否会报错-->
<select id="findUserNew" resultType="com.cnzz.mybatis.PO.UserPO">
SELECT * FROM user
<where>
<if test="idCard !=null and idCard!=''">
and id_card=#{idCard}
</if>
<if test="name !=null and name!=''">
and `name`=#{name}
</if>
<if test="age !=null">
and age=#{age}
</if>
<if test="sex !=null">
and sex=#{sex}
</if>
</where>
;
</select>