索引失效的情况以及对应解决方案
失效的第1种情况:
select * from emp where ename like ‘%T’;
ename上即使添加了索引,也不会走索引,为什么?
原因是因为模糊匹配当中以“%”开头了,mysql找不到。
解决方案:尽量避免模糊查询的时候以“%”开始。这是一种优化的手段/策略。
失效的第2种情况:
使用or的时候会失效,如果使用or那么要求or两边的条件字段都要有索引,才会走索引,如果or其中一边有一个字段没有索引,那么另一个字段上的索引也会失效。
解决方案:
不建议使用or,所以这就是为什么不建议使用or的原因。
或使用union联合查询。
举例:
dept表,loc字段有索引,deptname字段没有索引
select * from dept where loc = ‘福建’ or deptname = ‘信息部’;
查询位于福建的或者信息部的部门信息
以上sql语句,由于deptname没有索引,会导致loc的索引失效,可以使用union联合查询:
select * from dept where loc = ‘福建’
union
select * from dept where deptname = ‘信息部’;
这样loc字段的索引还是生效的。
失效的第3种情况:
使用复合索引的时候,没有用到左侧的字段作为查找条件,索引失效
什么是复合索引?
两个字段,或者更多的字段联合起来添加一个索引,叫做复合索引。
create index emp_job_sal_index on emp(job,sal);
索引正常:explain select * from emp where job = ‘MANAGER’;
索引失效:explain select * from emp where sal = 800;
失效的第4种情况:
在where当中索引列参加了运算,索引失效。
create index emp_sal_index on emp(sal);
索引正常:explain select * from emp where sal = 800;
索引失效:explain select * from emp where sal+1 = 800;
失效的第5种情况:
在where当中索引列使用了函数
ename字段有索引
explain select * from emp where lower(ename) = ‘smith’;