- 当我们使用左或者左右模糊匹配的时候,也就是 like %xx 或者 like %xx% 这两种方式都会造成索引失效。
- 有时候我们会用一些 MySQL 自带的函数来得到我们想要的结果,这时候要注意了,如果查询条件中对索引字段使用函数,就会导致索引失效。例如:
select * from t_user where length(name)=6;
- 在查询条件中对索引进行表达式计算,也是无法走索引的。例如:
select * from t_user where id + 1 = 10;
- 对索引隐式类型转换, 如果索引字段是字符串类型,但是在条件查询中,输入的参数是整型的话,你会在执行计划的结果发现这条语句会走全表扫描。例如,表结构如下:
列:
索引:
前置:mysql中,字符串与数字进行对比的时候,会将字符串转换成数字。
对其执行:select * from tb_test_index where phone = 111121 会走全表扫描,因为phone字段是varchar类型,条件字段的值是数字类型,会对phone进行隐式转换,相当于在表达式的左边对phone进行转换。表达式类似于: select * from tb_test_index where CAST(phone AS signed int) = 111121
因为对索引使用了函数,所以会走全表扫描
对其执行:select * from tb_test_index where number = "1" 不会走全表扫描,因为number本身是数值类型,将表达式的值转换为数值类型,并没有对索引列进行函数运算。表达式类似:
select * from tb_test_index where number = CAST("1" AS signed int) ,所以会走索引
- 联合索引非最左匹配
如果有c1,c2,c3 3个索引列,为其创建联合索引(c1,c2,c3),条件中,必须带上c1列,不然会进行全表扫描。
如下组合可以命中索引:
select * from tb_test_index where c1 = "1"
select * from tb_test_index where c1 = "1" and c2 ="2"
select * from tb_test_index where c1 = "1" and c3 ="2"
select * from tb_test_index where c1 = "1" and c2 ="2" and c3="3"
其他的组合都不能命中索引
- where 子句中的OR
select * from tb_test_index where phone = "111121" or sex = "1"。
如果phone和sex都是索引列,则会走索引,如其中一个不是,就不会走索引。