记一次,不亦云,索引失效[组合索引]

结合上一篇,当建立组合索引时:

场景1 :使用组合索引中的列均出现在条件中

 explain SELECT hd.id,hd.create_time,
       hd.name,
       hd.phone,
       hd.sex,
       hd.nationality,
       hd.temprature,
       hd.contact,
       hd.test_time,
       case when hd.idcard = '' then '护照' else '身份证' end            idcardtype,
       case when hd.idcard = '' then hd.passport else hd.idcard end idcard,
       oe.name                                                      office_name
FROM health_data hd
         left join office oe on oe.id = hd.office_id
WHERE (test_time > 1 and hd.del_flag = 0 and hd.create_time between '2021-05-01 00:00:00' and '2021-06-02 00:00:00' )
  AND `hd`.`office_id` IN
      ('0215e9e09572476abb1e24a467153c40')
ORDER BY hd.create_time desc ;

explain:

 使用到了索引,索引生效。

场景二:当组合索引中除第一索引外两个出现在检索条件中:

SQL:

 explain SELECT hd.id,hd.create_time,
       hd.name,
       hd.phone,
       hd.sex,
       hd.nationality,
       hd.temprature,
       hd.contact,
       hd.test_time,
       case when hd.idcard = '' then '护照' else '身份证' end            idcardtype,
       case when hd.idcard = '' then hd.passport else hd.idcard end idcard,
       oe.name                                                      office_name
FROM health_data hd
         left join office oe on oe.id = hd.office_id
WHERE ( hd.del_flag = 0 and hd.create_time between '2021-05-01 00:00:00' and '2021-06-02 00:00:00' )
  AND `hd`.`office_id` IN
      ('0215e9e09572476abb1e24a467153c40')
ORDER BY hd.create_time desc ;

explain:

 索引失效。

场景三:当组合索引中第一索引与其他索引出现在检索条件中:

 索引生效。

场景四:当组合索引中仅第一索引出现在检索条件中:

索引生效。

总结:组合索引使用中,当条件查询中不包含第一索引时,组合索引不生效,当包含第一索引列与其他任意列时,索引皆生效。 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值