案例 | 原因 |
---|---|
一 | 给定范围的索引查询range会让后面的索引失效 |
二 | 复合索引最左边的列索引要作为查询索引条件,否则整个复合索引失效,当最左边的列索引作为查询索引条件时,从左到右只要中间哪个列索引不作为查询索引条件时,后面的索引就失效 |
案例二 中的(6)也有说明 排序 和 查找 两个要分清楚 | |
三 | 在索引列上做任何操作(计算,函数,类型转换),会导致索引失效 |
四 | 到查询字段不要写*号,写字段名,*号会使索引失效 |
五 | 索引列作为查找条件,使用不等于(!=或<>)的时候会使索引失效 |
六 | 索引列作为查找条件,使用 is null , is not null 的时候会使索引失效 |
七 | 索引列作为查找条件,使用 like以通配符开头 % 的时候会使索引失效 |
八 | 这里旧的说法 or会让索引失效, 我的MYSQL版本5.5.57,or并不会让索引失效,具体哪个版本会出现这个问题,欢迎指出 |
# 查询员工首姓为Mary且租用日期大于 1987-02-07 的所有员工并按照生日降序排序取第一个员工数据
explain select * from employees where first_name = 'Mary' and hire_date > date('1987-02-07') order by birth_date desc limit 1
#创建复合索引
create index idx_employess_fhb on employees(first_name,hire_date,birth_date)
#查看索引
show index from employees
#删掉索引
drop index idx_employess_fhb on employees
#创建新的索引
create index idx_employess_fb on employees(first_name,birth_date)
#上面的案例一有旧的索引记得删掉,再创建这个新的
create index idx_employess_fhb on employees(first_name,hire_date,birth_date)
(1)
explain select * from employees where first_name = 'Koblick'
(2)
explain select * from employees where first_name = 'Koblick' and hire_date = date('19780-07-22')
(3)
explain select * from employees where first_name = 'Koblick' and birth_date = date('19780-07-22')
(4)
explain select * from employees where first_name = 'Koblick' and birth_date = date('19780-07-22') and hire_date = date('19780-07-22')
(5)
explain select * from employees where birth_date = date('19780-07-22')
explain select * from employees where hire_date = date('19780-07-22') and birth_date = date('19780-07-22')
(6)
explain select * from employees where first_name = 'Koblick' and birth_date = date('19780-07-22') order by hire_date
explain select * from employees where left(first_name,7) = 'Koblick'
explain select * from employees where first_name = 'Koblick' and DATE_FORMAT(hire_date,'YYYY-MM-dd') = '19780-07-22'
explain select * from employees where first_name=2000
(1)用了left函数 索引失效
(2)用了DATE_FORMAT函数 hire_date索引失效,所以key_len少了3长度
(3)因为 first_name 是 varchar 类型,2000是int类型,他会自动进行一个类型转换
explain select * from employees where first_name = 'Mary'
explain select emp_no,first_name from employees where first_name = 'Mary'
explain select * from employees where first_name != 'Mary'
explain select * from employees where first_name <> 'Mary'
explain select * from employees where first_name is null
explain select * from employees where first_name is not null
explain select * from employees where first_name like '%Mary'
explain select * from employees where first_name like '%Mary'
explain select * from employees where first_name like 'Mary'
explain select emp_no,first_name from employees where first_name like '%Mary'
explain select emp_no,birth_date from employees where first_name like '%Mary'
explain select emp_no,last_name from employees where first_name like '%Mary'