您的位置:首页 > 数据库 > MySQL

MySQL执行计划与索引详解

2018-10-28 13:09 453 查看

MySQL执行计划与索引详解

  • 索引最佳实践

  • 使用
    EXPLAIN
    关键字可以模拟优化器执行SQL语句,从而知道MySQL是 如何处理你的SQL语句的。分析你的查询语句或是结构的性能瓶颈 。

    举个栗子

    在 select 语句之前增加 explain 关键字,MySQL 会在查询上设置一个标记,执行查询时,会返回执行计划的信息,而不是执行这条SQL(如果 from 中包含子查询,仍会执行该子查询,将结果放入临时表中)

    建表语句

    DROP TABLE IF EXISTS `sys_user`;
    CREATE TABLE `sys_user` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(45) DEFAULT NULL,
    `update_time` datetime DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    INSERT INTO `sys_user`(`id`, `name`, `update_time`) VALUES (1, 'zhangsan', '2018-10-24 11:12:14');
    INSERT INTO `sys_user`(`id`, `name`, `update_time`) VALUES (2, 'lisi', '2018-10-24 11:12:47');
    INSERT INTO `sys_user`(`id`, `name`, `update_time`) VALUES (3, 'wangwu', '2018-10-24 11:12:54');
    
    DROP TABLE IF EXISTS `sys_role`;
    CREATE TABLE `sys_role` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(45) DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `idx_name` (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    INSERT INTO `test`.`sys_role`(`id`, `name`) VALUES (1, '管理员');
    INSERT INTO `test`.`sys_role`(`id`, `name`) VALUES (2, '普通用户');
    
    DROP TABLE IF EXISTS `sys_user_role`;
    CREATE TABLE `sys_user_role` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `user_id` int(11) DEFAULT NULL,
    `role_id` int(11) DEFAULT NULL,
    `remark` varchar(255) DEFAULT NULL,
    PRIMARY KEY (`id`),
    KEY `idx_role_user_id` (`role_id`,`user_id`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    INSERT INTO `test`.`sys_user_role`(`id`, `user_id`, `role_id`, `remark`) VALUES (1, 1, 1, NULL);
    INSERT INTO `test`.`sys_user_role`(`id`, `user_id`, `role_id`, `remark`) VALUES (2, 1, 2, NULL);
    INSERT INTO `test`.`sys_user_role`(`id`, `user_id`, `role_id`, `remark`) VALUES (3, 2, 2, NULL);

    简单使用

    explain select * from sys_user

    explain中字段详解

    一、id列

    • id列的编号是 select 的序列号,有几个 select 就有几个id,并且id的顺序是按 select 出现的顺序增长的
    • MySQL将 select 查询分为简单查询(SIMPLE)和复杂查询(PRIMARY),复杂查询分为三类:简单子查询、派生表(from语句中的子查询)、union 查询
    • id列越大执行优先级越高,id相同则从上往下执行,id为NULL最后执行
    1. 简单子查询
    explain select (select 1 from sys_user limit 1) from sys_role;

    1. from子句中的子查询
    explain select id from (select id from sys_role) as temp;

    1. union查询
    explain select id from sys_user union all select id from sys_role;


    union结果总是放在一个匿名临时表中,临时表不在SQL中出现,因此它的id是NULL

    二. select_type列

    select_type 表示对应行是简单还是复杂的查询,如果是复杂的查询,又是上述三种复杂查询中的哪一种。

    1. simple:简单查询。查询不包含子查询和union
    explain select * from sys_user where id = 2;

    1. primary:复杂查询中最外层的 select
    2. subquery:包含在 select 中的子查询(不在 from 子句中)
    3. derived:包含在 from 子句中的子查询。MySQL会将结果存放在一个临时表中,也称为派生表(derived的英文含义)

    用这个例子来了解 primary、subquery 和 derived 类型

    explain select (select 1 from sys_user where id = 1) from (select * from sys_role where id = 1) der

    1. union:在 union 中的第二个和随后的 select
    2. union result:从 union 临时表检索结果的 select

    用这个例子来了解 union 和 union result 类型

    explain select 1 union all select 1;

    三、table列

    • 这一列表示 explain 的一行正在访问哪个表
    • 当 from 子句中有子查询时,table列是 格式,表示当前查询依赖 id=N 的查询,于是先执行 id=N 的查询
    • 当有 union 时,UNION RESULT 的 table 列的值为<union1,2>,1和2表示参与 union 的 select 行id

    四、type列

    • 这一列表示关联类型或访问类型,即MySQL决定如何查找表中的行,查找数据行记录的大概范围
    • 依次从最优到最差分别为:system > const > eq_ref > ref > range > index > ALL
    • 一般来说,得保证查询达到range级别,最好达到ref

    NULL: mysql能够在优化阶段分解查询语句,在执行阶段用不着再访问表或索引。例如:在索引列中选取最小值,可以单独查找索引来完成,不需要在执行时访问表

    explain select min(id) from sys_user;

    const, system:mysql能对查询的某部分进行优化并将其转化成一个常量(可以看show warnings 的结果)。用于 primary key 或 unique key 的所有列与常数比较时,所以表最多有一个匹配行,读取1次,速度比较快。system是const的特例,表里只有一条元组匹配时为system

    explain extended select * from (select * from sys_role where id = 1) tmp;

    eq_ref:primary key 或 unique key 索引的所有部分被连接使用 ,最多只会返回一条符合条件的记录。这可能是在 const 之外最好的联接类型了,简单的 select 查询不会出现这种 type

    explain select * from sys_user_role left join sys_role on sys_user_role.role_id = sys_role.id;

    ref:相比 eq_ref,不使用唯一索引,而是使用普通索引或者唯一性索引的部分前缀,索引要和某个值相比较,可能会找到多个符合条件的行

    1. 简单 select 查询,name是普通索引(非唯一索引)
    explain select * from sys_role where name = "管理员"

    1. 关联表查询,idx_role_user_id是user_id和role_id的联合索引,这里使用到了sys_user_role的左边前缀role_id部分
    explain select name from sys_role left join sys_user_role on sys_role.id = sys_user_role.role_id;

    range:范围扫描通常出现在 in(), between ,> ,<, >= 等操作中。使用一个索引来检索给定范围的行

    explain select * from sys_user where id > 1;

    index:扫描全表索引,这通常比ALL快一些。(index是从索引中读取的,而all是从硬盘中读取)

    explain select * from sys_role;

    ALL:即全表扫描,意味着mysql需要从头到尾去查找所需要的行。通常情况下这需要增加索引来进行优化了

    explain select * from sys_user;

    五、possible_keys列

    • 这一列显示查询可能使用哪些索引来查找
    • explain 时可能出现 possible_keys 有列,而 key 显示 NULL 的情况,这种情况是因为表中数据不多,mysql认为索引对此查询帮助不大,选择了全表查询
    • 如果该列是NULL,则没有相关的索引。在这种情况下,可以通过检查 where 子句看是否可以创造一个适当的索引来提高查询性能,然后用 explain 查看效果

    六、key列

    • 这一列显示mysql实际采用哪个索引来优化对该表的访问
    • 如果没有使用索引,则该列是 NULL。如果想强制mysql使用或忽视possible_keys列中的索引,在查询中使用 force index、ignore index

    七、key_len列

    • 这一列显示了mysql在索引里使用的字节数,通过这个值可以算出具体使用了索引中的哪些列

    举例来说,film_actor的联合索引 idx_film_actor_id 由 film_id 和 actor_id 两个int列组成,并且每个int是4字节。通过结果中的key_len=4可推断出查询使用了第一个列:film_id列来执行索引查找

    explain select * from sys_user_role where sys_user_role.role_id = 2;

    key_len计算规则如下:

    • 字符串 char(n):n字节长度
    • varchar(n):2字节存储字符串长度,如果是utf-8,则长度 3n + 2
  • 数值类型
      tinyint:1字节
    • smallint:2字节
    • int:4字节
    • bigint:8字节
  • 时间类型
      date:3字节
    • timestamp:4字节
    • datetime:8字节
  • 如果字段允许为 NULL,需要1字节记录是否为 NULL
  • 索引最大长度是768字节,当字符串过长时,mysql会做一个类似左前缀索引的处理,将前半部分的字符提取出来做索引
  • 八、ref列

    • 这一列显示了在key列记录的索引中,表查找值所用到的列或常量,常见的有:const(常量),字段名(例:sys_role.id)

    九、 rows列

    • 这一列是mysql估计要读取并检测的行数,注意这个不是结果集里的行数。

    十、Extra列

    这一列展示的是额外信息。常见的重要值如下:

    1. Using index:查询的列被索引覆盖,并且where筛选条件是索引的前导列,是性能高的表现。一般是使用了覆盖索引(索引包含了所有查询的字段)。对于innodb来说,如果是辅助索引性能会有不少提高
    explain select name from sys_role;

    1. Using where:查询的列未被索引覆盖,where筛选条件非索引的前导列
    explain select * from sys_user where name = "zhangsan";

    1. Using where Using index:查询的列被索引覆盖,并且where筛选条件是索引列之一但不是索引的前导列,意味着无法直接通过索引查找来查询到符合条件的数据
    explain select role_id from sys_user_role where user_id = 1;

    1. NULL:查询的列未被索引覆盖,并且where筛选条件是索引的前导列,意味着用到了索引,但是部分字段未被索引覆盖,必须通过“回表”来实现,不是纯粹地用到了索引,也不是完全没用到索引
    explain select * from sys_user_role where role_id = 1;

    1. Using index condition:查与Using where类似,查询的列不完全被索引覆盖,where条件中是一个前导列的范围
    explain select * from sys_user_role where role_id >1 ;

    1. Using temporary:mysql需要创建一张临时表来处理查询。出现这种情况一般是要进行优化的,首先是想到用索引来优化
    sys_user.name 没有索引,此时创建临时表来distinct
    explain select distinct name from sys_user;

    sys_role.name 建立了索引,查询时 Extra 是 using index,没有临时表
    explain select distinct name from sys_role;

    1. Using filesort:mysql 会对结果使用一个外部索引排序,而不是按索引次序从表里读取行。此时mysql会根据联接类型浏览所有符合条件的记录,并保存排序关键字和行指针,然后排序关键字并按顺序检索行信息。这种情况下一般也是要考虑使用索引来优化的
    sys_user.name 没有建立索引,会扫面整个表
    explain select * from sys_user order by name;

    sys_role.name 建立了索引,此时Extra 是 using index
    explain select * from sys_role order by name;

    索引最佳实践

    表结构

    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` (`name`,`age`,`position`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT 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('HanMeimei', 23,'dev',NOW());
    INSERT INTO employees(name,age,position,hire_time) VALUES('Lucy',23,'dev',NOW());

    最佳实践

    一、全值匹配

    explain select * from employees where name = "lilei";

    explain select * from employees where name = "lilei" and age = 22;

    explain select * from employees where name = "lilei" and age = 22 and position = 'manager';

    二、最佳左前缀法则

    如果索引了多列,要遵守最左前缀法则。指的是查询从索引的最左前列开始并且不跳过索引中的列

    -- 跳过了 name索引
    explain select * from employees where age = 22 and position ='manager';
    -- 跳过了 name 和 age索引
    explain select * from employees where position = 'manager';
    -- 使用了索引
    explain select * from employees where name = 'LiLei';

    三、不在索引列上做任何操作(计算、函数、(自动or手动)类型转换),会导致索引失效而转向全表扫描

    -- 使用索引
    explain select * from employees where name = 'LiLei';
    -- 未使用索引
    explain select * from employees where left(name,3) = 'LiLei';

    四、存储引擎不能使用索引中范围条件右边的列

    -- 使用全部索引
    explain select * from employees where name = 'LiLei' and age = 22 and position ='manager';

    -- 未使用全部索引
    explain select * from employees where name = 'LiLei' and age > 22 and position ='manager';

    五、尽量使用覆盖索引(只访问索引的查询(索引列包含查询列)),减少select *语句

    explain select name,age from employees where name = 'LiLei' and age = 22 and position ='manager';

    explain select * from employees where name = 'LiLei' and age = 22 and position ='manager';

    六、mysql在使用不等于(!=或者<>)的时候无法使用索引会导致全表扫描

    explain select * from employees where name != 'LiLei';

    七、is null,is not null 也无法使用索引

    explain select * from employees where name is null;

    八、like以通配符开头(’$abc…’)mysql索引失效会变成全表扫描操作

    explain select * from employees where name like '%LiLei';

    explain select * from employees where name like 'LiLei%';

    问题:解决like’%字符串%'索引不被使用的方法?

    • 使用覆盖索引,查询字段必须是建立覆盖索引字段
    explain select name,age,position from employees where name like '%LiLei%';

    • 当覆盖索引指向的字段是varchar(380)及380以上的字段时,覆盖索引会失效!

    九、字符串不加单引号索引失效

    -- 使用索引
    explain select * from employees where name = '1000';
    -- 索引失效
    explain select * from employees where name = 1000;

    十、少用or,用它连接时很多情况下索引会失效

    explain select * from employees where name = 'LiLei' or name = 'HanMeimei';

    十一、总结

    假设index(a,b,c)

    where 语句 索引是否被使用
    where a = 3 Y,使用到 a
    where a = 3 and b = 5 Y,使用到 a,b
    where a = 3 and b = 5 and c = 4 Y,使用到 a,b,c
    where b = 3 或者 where b = 3 and c = 4 或者 where c = 4 N
    where a = 3 and c =5 使用到了a,但是c没有,b中间断了
    where a = 3 and b > 4 and c = 5 使用到了a和b,c不能用在范围之后,b断了
    where a = 3 and b like ‘kk%’ and c = 4 Y,使用到了a,b,c
    where a = 3 and b like ‘%kk’ and c = 4 Y,只用到a
    where a = 3 and b like ‘%kk%’ and c = 4 Y,只用到a
    where a = 3 and b like ‘k%kk%’ and c = 4 Y,只用到a,b,c
    • like KK%相当于=常量,%KK和%KK% 相当于范围
    阅读更多
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: