排查索引失效的原因是至关重要的,主要有以下方面:
CREATE TABLE `student_info` (
`student_id` int(11) NOT NULL AUTO_INCREMENT,
`student_name` varchar(50) NOT NULL,
`student_age` int(11) DEFAULT NULL,
`enrollment_date` datetime DEFAULT NULL,
PRIMARY KEY (`student_id`),
UNIQUE KEY `student_name` (`student_name`),
KEY `student_age` (`student_age`),
KEY `enrollment_date` (`enrollment_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
student_info
有四个字段上定义了索引:
student_id
student_name
student_age
和 enrollment_date
。explain select * from student_info where student_age=21;
explain select * from student_info where student_age+1 =21;
explain select * from student_info where enrollment_date = '2022-09-04 08:00:00';
explain select * from student_info where YEAR(enrollment_date) = 2022;
student_name
索引explain select * from student_info where student_name='Helen' and student_age>15;
explain select * from student_info where student_name='Helen' or student_age>15;
explain select * from student_info where student_name='Helen' or student_age=18;
!=
比较有可能会导致不走索引,但如果对 id 进行 != 比较,是有可能走索引的。!=
比较是否走索引,与索引的选择、数据分布情况有关,不单是由于查询包含 !=
而引起的。IN
的时候,有可能走索引,也有可能不走索引。当在 IN
的取值范围比较大的时候有可能会导致索引失效,走全表扫描(NOT IN
和 IN
的失效场景相同)。索引失效情况
type
值为 all
、key 为 null
,extra = Using where
此时是索引失效了此时就需要排查索引失效的原因
MySQL中什么情况下会出现索引失效?如何排查索引失效?
回答