全值匹配(索引最佳)
explain select * from user where name = 'zhangsan' and age = 20 and pos = 'cxy' and phone = '18730658760';
和索引顺序无关,MySQL底层的优化器会进行优化,调整索引的顺序
explain select * from user where name = 'zhangsan' and age = 20 and pos = 'cxy' and phone = '18730658760';
1、违反最左前缀法则
如果索引有多列,要遵守最左前缀法则
即查询从索引的最左前列开始并且不跳过索引中的列
explain select * from user where age = 20 and phone = '18730658760' and pos = 'cxy';
2、在索引列上做任何操作
如计算、函数、(自动or手动)类型转换等操作,会导致索引失效从而全表扫描
explain select * from user where left(name,5) = 'zhangsan' and age = 20 and phone = '18730658760';
3、索引范围条件右边的列
索引范围条件右边的索引列会失效
explain select * from user where name = 'zhangsan' and age > 20 and pos = 'cxy';
4、尽量使用覆盖索引
只访问索引查询(索引列和查询列一致),减少select*
explain select name,age,pos,phone from user where age = 20;
5、使用不等于(!=、<>)
mysql在使用不等于(!=、<>)的时候无法使用索引会导致全表扫描(除覆盖索引外)
explain select * from user where age != 20;
explain select * from user where age <> 20;
更多MySQL的索引失效总结,请查看原文:https://developer.aliyun.com/article/741403?utm_content=g_1000097870