mybatis where 1=1导致索引失效问题探究

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>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值