结合上一篇,当建立组合索引时:
场景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:
索引失效。
场景三:当组合索引中第一索引与其他索引出现在检索条件中:
索引生效。
场景四:当组合索引中仅第一索引出现在检索条件中:
索引生效。
总结:组合索引使用中,当条件查询中不包含第一索引时,组合索引不生效,当包含第一索引列与其他任意列时,索引皆生效。