本文以 employees
表为例子,结合具体的索引运用实践案例,通过分析 EXPLAIN
关键字获取执行计划,来验证我们这些索引实践。如果是执行计划相关的详细信息,大家可以参考 mysql 官网 explain 介绍。
mysql 版本: 5.7.23
CREATE TABLE employees (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
age int(11) NOT NULL DEFAULT '0' COMMENT '年龄',
position varchar(20) NOT NULL DEFAULT '' COMMENT '职位',
hire_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入职时间',
PRIMARY KEY (id),
KEY idx_name_age_position USING BTREE (name, age, position)
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARSET = utf8 COMMENT '员工记录表';
INSERT INTO employees (name, age, position, hire_time) VALUES ('LiLei', 22, 'manager', NOW());
INSERT INTO employees (name, age, position, hire_time) VALUES ('WaKen', 23, 'dev', NOW());
INSERT INTO employees (name, age, position, hire_time) VALUES ('Lucy', 23, 'dev', NOW());
下面是一个复合索引的是示意图
对于全值匹配,就是查询条件能够命中索引的全部列,或者复合索引需要命中左边的数据
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei';
image.png
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22;
image.png
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position ='manager';
image.png
如果索引了多列,要遵守最左前缀法则。指的是查询从索引的最左前列开始并且不跳过索引中的列。
EXPLAIN SELECT * FROM employees WHERE age = 22 AND position ='manager';
image.png
EXPLAIN SELECT * FROM employees WHERE position = 'manager';
image.png
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei';
image.png
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei';
image.png
EXPLAIN SELECT * FROM employees WHERE left(name,3) = 'LiLei';
image.png
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 22 AND position ='manager';
image.png
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age > 22 AND position ='manager';
image.png
对于 select 指定字段查询,如果查询的所有列都是索引上的数据,那么可以减少 “回表”。查询的效率高于 select *
explain select name,age from employees where name = 'Lilei' and age = 23 and position= 'manage';
EXPLAIN SELECT * FROM employees WHERE name= 'LiLei' AND age = 23 AND position ='manager';
image.png
EXPLAIN SELECT * FROM employees WHERE name != 'LiLei';
image.png
因为在 mysql 变长的数据类型中,如 varchar 。null 不会存储,它需要一个额外的标志位来存储。所以如果我们使用 is null , is not null 是无法使用索引的。所以我们在 DDL 语句中尽量让每个字段都有默认值。
EXPLAIN SELECT * FROM employees WHERE name is null;
image.png
EXPLAIN SELECT * FROM employees WHERE name like '%Lei';
image.png
EXPLAIN SELECT * FROM employees WHERE name like 'Lei%';
问题:解决like'%字符串%'索引不被使用的方法?a)使用覆盖索引,查询字段必须是建立覆盖索引字段
EXPLAIN SELECT name,age,position FROM employees WHERE name like '%Lei%';
b)当覆盖索引指向的字段是varchar(380)及380以上的字段时,覆盖索引会失效!
字符串不加单引号索引失效
EXPLAIN SELECT * FROM employees WHERE name = '1000';
image.png
EXPLAIN SELECT * FROM employees WHERE name = 1000;
image.png
EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' or name = 'HanMeimei';
image.png
like KK%相当于=常量,%KK和%KK% 相当于范围 下面是常见的几种索引查询失效或者,可用的判定
01索引优化案例.png