索引失效的十种情况,建议全部记住
1)全值匹配我最爱
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023164735004-642353727.png)
2)最佳左前缀原则(如果索引了多列,要遵守最左前缀法则。指的是查询从索引的最左前列开始并且不跳过索引中的列。)
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023164758801-948838214.png)
3)不在索引上做任何的操作(计算,函数(自动or手动)类型转换)会导致索引失效而转为全表的扫描
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023164922973-1732381649.png)
4)存储引擎不能使用索引条件范围中右边的列
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023164959566-1528504210.png)
5)尽量使用覆盖索引(只访问索引的查询(索引的列和查询的列一致),减少select * )
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023165031285-299061217.png)
6)mysql中使用不等于(!=或者<>)会导致索引失效而扫描全表
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023165106769-2133150663.png)
7)is null , is not null 也无法使用索引
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023165144035-1561468021.png)
8)like以通配符开头的(%AA...)也会导致索引失效,而扫描全表
问题:解决 like %字符串%时索引不被使用的方法:建立一个符合索引,同时在查询时查询索引对应的列
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023165233379-293557073.png)
9)字符串不加单引号,导致索引失效
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023165321707-1651410700.png)
10)少用or,用它时索引也会失效
![](https://images2017.cnblogs.com/blog/1253382/201710/1253382-20171023165359410-322255814.png)
总结:
假设index(a,b,c)
Where语句 索引是否被使用
where a = 3 Y,使用到a
where a = 3 and b = 5 Y,使用到a,b
where a = 3 and b = 5 and c = 4 Y,使用到a,b,c
where b = 3 | where b = 3 and c = 4 | where c = 4 N
where a = 3 and c = 5 使用到a, 但是C不可以,中间断了
where a = 3 and b > 4 and c = 7 使用到a和b, c在范围之后,断了
where a = 3 and b like 'kk%' and c = 4 同上