MySQL不走索引的情况


1.索引列参与了计算,不走索引!

  不走索引情况:SELECT `username` FROM `t_user` WHERE age+10=30;

  走索引情况,因为没有在列上运算:SELECT `username` FROM `t_user` WHERE age=30-10;

2.索引列上使用了函数,不走索引!

  不走索引情况:SELECT username FROM t_user WHERE concat(username,'1') ='admin1';

  走索引情况,因为没有在列上使用函数:SELECT username FROM t_user WHERE username =concat('admin','1');

3.索引列使用了Like %XXX或Like %XXX%,不走索引!

  不走索引情况:select * from user where username like '%mysql测试'    select * from user where username like '%mysql测试%'

  走索引情况: select * from user where username like 'mysql测试%' ;

4.隐式转换——字符串列与数字比较,不走索引!

  title字段为varchar

  不走索引情况:select * from job j where j.`title` = 1

  走索引情况,因为比较的是字符:select * from job j where j.`title` = '1'

5.尽量避免 OR 操作,只要有一个字段没有索引,改语句就不走索引,不走索引!

  select * from t_user where username = 'mysql测试' or password ='123456'

  当只有username有索引,则不走索引。

  当username和password都有索引,则走索引。

6.使用!= 或者 <> 判断,不走索引!(<>是!=另一种表达形式,其效果都相同)

  不走索引情况:select * from t_user where username <> 'mysql测试'

         select * from t_user where username != 'mysql测试'

7.where中使用 is null,is not null也无法使用索引,不走索引!

  不走索引情况:select from t_user where username is null

         select from t_user where username is not null

8.不符合最左匹配原则的符合索引写法,不走索引!

  最左匹配原则:

    当遇到范围查询(>、<、between、like)就会停止匹配

    在 InnoDB 中联合索引只有先确定了前一个(左侧的值)后,才能确定下一个值。如果其中一个没有连续匹配上,那么联合索引中使用范围查询的字段后的索引在该条 sql 中都不会起作用。

    in= 都可以乱序,比如有索引(a,b,c),语句 select * from t where c =1 and a=1 and b=1,这样的语句也可以用到最左匹配,因为 mysql 中有一个优化器,他会分析 SQL 语句,将其优化成索引可以匹配的形式,即

select * from t where a =1 and a=1 and c=1

  例如定义了符合索引(a,b,c)

  走索引的情况:select * from t where a=1 and b=1 and c =1;(全部匹配,走索引)

         select from where c=and b=and a =1; (MySQL server层优化器会帮我们自动优化为 a,b,c,全部匹配,走索引)

         select * from t where a=1 and b=1;(匹配到前缀a,b,走索引)

         select * from t where a=1;(匹配到前缀a,走索引)

  不走索引的情况:select * from t where b=1 and c=1;(没匹配到a,碰到了b和c 结束匹配)

          select * from t where a=1 and c=1;(匹配到a后没有匹配到b却碰到了c 结束匹配)

          select from where a=and b>and c =1; (a,b用到了复合索引,c没有)

 

最后值得一提的是有时候我们的正常使用的大于>,小于<都不会走索引,这跟数据大小和数据存储空间位置与索引位置有关系,有时候我们MySQL优化器会进行择优选择,来选择走索引还是直接去引擎寻找数据,我们需要做的就是避免以上语法情况。

          


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM