说明:在SQL优化时,建立组合索引,我们需要知道最左匹配失效的情况,本文通过实例介绍最左匹配原则失效;
建立组合索引
如下,是一张大表,有1000万条数据;
对表中password、sex和email字段建立组合索引。注意,建立组合索引,应当把区别度高的字段放在前面,如以上三个字段,密码字段是区别度最高的,故放在最前面;
alter table user add index idx_compose (password, sex, email);
查看执行计划
使用explain关键字,分别查询这些字段进行查询,查看执行计划;
password、sex、email字段,and查询
explain select * from user where password = 'c81e728d9d4c2f636f067f89cc14862c' and sex = 'male' and email = 'zhangsan2@'
走了索引;
对password、sex字段,and查询
explain select * from user where password = 'c81e728d9d4c2f636f067f89cc14862c' and sex = 'male'
走了索引;
对password、email字段,and查询
explain select * from user where password = 'c81e728d9d4c2f636f067f89cc14862c' and email = 'zhangsan2@'
只有一个字段走了索引;
单独对password、sex、email字段,and查询;
explain select * from user where password = 'c81e728d9d4c2f636f067f89cc14862c' and email = 'zhangsan2@';
explain select * from user where sex = 'male';
explain select * from user where email = 'zhangsan2@';
将字段调换,如sex、email、password,and查询;
explain select * from user where sex = 'male' and email = 'zhangsan2@' and password = 'c81e728d9d4c2f636f067f89cc14862c';
还是都走了索引;
结论
如对表的A、B、C字段建立了组合索引,最左匹配原则失效是指:
当查询的字段从左开始,只有匹配了组合索引字段顺序的字段才会走索引,如AB字段,则均会走索引;AC字段,则A字段会走索引;BC字段,则均不会走索引;单独的A、B、C字段查询,因为只有A字段匹配上了组合索引,会走索引,B、C字段查询均不会走索引。
另外,最左匹配不包括SQL的书写顺序,如根据BCA字段查询,也会因为MySQL自身的优化,而走索引查询。