索引失效

1.索引失效

  

2.全职匹配

  索引都加上

create index idx_all on employee(`name`, dep_id, age);

  然后写sql的时候,所有的索引都加上,则是全职匹配

3.最佳左前缀法则

  如果前面的跳过,则后面的索引失效

  顺序就不再重要了

4.函数计算会导致索引失效

explain 
select * from employee where trim(age) = 10

  但是这样是可以走索引,后面说明,这里是实验:

explain 
select age from employee where trim(age) = 10

  

5.范围条件使得右边的索引失效

explain 
select * from employee where name = '鲁班' and dep_id >2 and age =1

  

  说明:

  age的索引是失效了,只有前面的索引没有失效

6.使用!=或者<>也会索引失效

  下面有好几个示例,结论是,如果不能让这个索引从前面失效,还是会使用index_all的

explain 
select * from employee where name != '鲁班' and dep_id =2 and age =1

  

   说明:

  走的是dep_id的索引

explain 
select * from employee where name = '鲁班' and dep_id = 4 and age != 10

  

explain 
select * from employee where name = '鲁班' and dep_id != 4 and age = 10

  

7.is not null也会失效

8.or也会导致索引的失效

9.like导致的失效

  如果百分号在后面,索引不会失效,但是要在前面会失效

explain 
select * from employee where name like '鲁%' 

  

二:解决方式

1.尽量使用覆盖索引

explain 
select age from employee where name like '%鲁' 

  

   说明:

  虽然,没有写name,但是也使用了索引

  但是发现,filtered并不好

  

原文地址:https://www.cnblogs.com/juncaoit/p/13326621.html