介绍mysql索引失效的情况

介绍mysql索引失效的情况,第1张

概述介绍mysql索引失效情况

@H_419_1@

mysql视频教程栏目索引失效的情况。

索引对于MysqL而言,是非常重要的篇章。索引知识点也巨多,要想掌握透彻,需要逐个知识点一一击破,今天来先来聊聊哪些情况下会导致索引失效。

图片总结版

相关免费学习推荐:mysql视频教程

全值匹配(索引最佳)
explain select * from user where name = 'zhangsan' and age = 20 and pos = 'cxy' and phone = '18730658760';

和索引顺序无关,MysqL底层的优化器会进行优化,调整索引的顺序explain select * from user where name = 'zhangsan' and age = 20 and pos = 'cxy' and phone = '18730658760';

1、违反最左前缀法则
如果索引有多列,要遵守最左前缀法则即查询从索引的最左前列开始并且不跳过索引中的列explain select * from user where age = 20 and phone = '18730658760' and pos = 'cxy';

2、在索引列上做任何 *** 作
如计算、函数、(自动or手动)类型转换等 *** 作,会导致索引失效从而全表扫描explain select * from user where left(name,5) = 'zhangsan' and age = 20 and phone = '18730658760';

3、索引范围条件右边的列
索引范围条件右边的索引列会失效explain select * from user where name = 'zhangsan' and age > 20 and pos = 'cxy';

4、尽量使用覆盖索引
只访问索引查询(索引列和查询列一致),减少select*explain select name,age,pos,phone from user where age = 20;

5、使用不等于(!=、<>)
MysqL在使用不等于(!=、<>)的时候无法使用索引会导致全表扫描(除覆盖索引外)explain select * from user where age != 20;explain select * from user where age <> 20;

6、like以通配符开头('%abc')
索引失效explain select * from user where name like '%zhangsan';

索引生效explain select * from user where name like 'zhangsan%';

7、字符串不加单引号索引失效
explain select * from user where name = 2000;

8、or连接
少用orexplain select * from user where name = '2000' or age = 20 or pos ='cxy';

9、order by
正常(索引参与了排序)explain select * from user where name = 'zhangsan' and age = 20 order by age,pos;备注:索引有两个作用:排序和查找
导致额外的文件排序(会降低性能)explain select name,age from user where name = 'zhangsan' order by pos;//违反最左前缀法则explain select name,age from user where name = 'zhangsan' order by pos,age;//违反最左前缀法则explain select * from user where name = 'zhangsan' and age = 20 order by created_time,age;//含非索引字段

10、group by
正常(索引参与了排序)explain select name,age from user where name = 'zhangsan' group by age;备注:分组之前必排序(排序同order by)

导致产生临时表(会降低性能)explain select name,pos from user where name = 'zhangsan' group by pos;//违反最左前缀法则explain select name,age from user where name = 'zhangsan' group by pos,age;//违反最左前缀法则explain select name,age from user where name = 'zhangsan' group by age,created_time;//含非索引字段

使用的示例数据
MysqL> show create table user \G******************************************************       table: userCreate table: CREATE table `user` (  `ID` int(10) NOT NulL auto_INCREMENT,  `name` varchar(20) DEFAulT NulL,  `age` int(10) DEFAulT '0',  `pos` varchar(30) DEFAulT NulL,  `phone` varchar(11) DEFAulT NulL,  `created_time` datetime DEFAulT NulL,  PRIMARY KEY (`ID`),  KEY `IDx_name_age_pos_phone` (`name`,`age`,`pos`,`phone`)) ENGINE=InnoDB DEFAulT CHARSET=utf8mb4 ColLATE=utf8mb4_0900_ai_ci

总结

以上是内存溢出为你收集整理的介绍mysql索引失效的情况全部内容,希望文章能够帮你解决介绍mysql索引失效的情况所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/1150381.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存