0
点赞
收藏
分享

微信扫一扫

索引失效的情况及解决(超详细)

贵州谢高低 2022-11-18 阅读 88

大家都知道,一条查询语句走了索引和没走索引的查询效率是非常大的,在我们建好了表,建好了索引后,但是一些不好的sql会导致我们的索引失效,下面介绍一下索引失效的几种情况

数据准备 

新建一张学生表,并添加id为主键索引,name为普通索引,(name,age)为组合索引

CREATE TABLE `student` (
  `id` int NOT NULL COMMENT 'id',
  `name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '姓名',
  `age` int DEFAULT NULL COMMENT '年龄',
  `birthday` datetime DEFAULT NULL COMMENT '生日',
  PRIMARY KEY (`id`),
  KEY `idx_name` (`name`) USING BTREE,
  KEY `idx_name_age` (`name`,`age`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

插入数据

INSERT INTO `student` VALUES (1, '张三', 18, '2021-12-23 17:12:44');
INSERT INTO `student` VALUES (2, '李四', 20, '2021-12-22 17:12:48');

1.查询条件中有or,即使有部分条件带索引也会失效

例:

explain SELECT * FROM `student` where id =1 

 此时命中主键索引,当查询语句带有or后

explain SELECT * FROM `student` where id =1 or birthday = "2021-12-23"

 发现此时type=ALL,全表扫描,未命中索引

总结:查询条件中带有or,除非所有的查询条件都建有索引,否则索引失效

2.like查询是以%开头

explain select * from student where name = "张三"

非模糊查询,此时命中name索引,当使用模糊查询后

explain select * from student where name like "%三"

 

 发现此时type=ALL,全表扫描,未命中索引

3.如果列类型是字符串,那在查询条件中需要将数据用引号引用起来,否则不走索引

explain select * from student where name = "张三"

此时命中name索引,当数据未携带引号后

explain select * from student where name = 2222

 此时未命中name索引,全表扫描

总结:字符串的索引字段在查询是数据需要用引号引用

4.索引列上参与计算会导致索引失效

explain select * from student where id-1 = 1

查询条件为id,但是并没有命中主键索引,因为在索引列上参与了计算 

正例

select * from student where id = 2

 总结:将参与计算的数值先算好,再查询

5.违背最左匹配原则

explain select * from student where age =18

age的索引是和建立再(name,age)组合索引的基础上,当查询条件中没有第一个组合索引的字段(name)会导致索引失效

正例

explain select * from student where age =18 and name ="张三"

 此时才会命中name和(name,age)这个索引

6.如果mysql估计全表扫描要比使用索引要快,会不适用索引

7.other

举报

相关推荐

0 条评论