MySQL高级-SQL优化步骤

在应用的的开发过程中,由于初期数据量小,开发人员写 SQL 语句时更重视功能上的实现,但是当应用系统正式上线后,随着生产数据量的急剧增长,很多 SQL 语句开始逐渐显露出性能问题,对生产的影响也越来越大,此时这些有问题的 SQL 语句就成为整个系统性能的瓶颈,因此我们必须要对它们进行优化,本章将详细介绍在 MySQL 中优化 SQL 语句的方法。
当面对一个有 SQL 性能问题的数据库时,我们应该从何处入手来进行系统的分析,使得能够尽快定位问题 SQL 并尽快解决问题。

1 查看SQL执行频率

MySQL 客户端连接成功后,通过 show [session|global] status 命令可以提供服务器状态信息。show [session|global] status 可以根据需要加上参数“session”或者“global”来显示 session 级(当前连接)的计结果和 global 级(自数据库上次启动至今)的统计结果。如果不写,默认使用参数是“session”。
下面的命令显示了当前 session 中所有统计参数的值:

mysql> show status like 'Com_______';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Com_binlog    | 0     |
| Com_commit    | 0     |
| Com_delete    | 0     |
| Com_insert    | 4     |
| Com_repair    | 0     |
| Com_revoke    | 0     |
| Com_select    | 5     |
| Com_signal    | 0     |
| Com_update    | 0     |
| Com_xa_end    | 0     |
+---------------+-------+
10 rows in set (0.04 sec)

此时查的是当前连接对应的信息,如果想查询全局的话,加上global:

show global status like 'Com_______';

如果是想查看innodb存储引擎的信息:

show status like 'Innodb_rows_%';

在这里插入图片描述
可以看出,当前数据库以查询为主。
Com_xxx 表示每个 xxx 语句执行的次数,我们通常比较关心的是以下几个统计参数。

参数 含义
Com_select 执行 select 操作的次数,一次查询只累加 1。
Com_insert 执行 INSERT 操作的次数,对于批量插入的 INSERT 操作,只累加一次。
Com_update 执行 UPDATE 操作的次数。
Com_delete 执行 DELETE 操作的次数。
Innodb_rows_read select 查询返回的行数。
Innodb_rows_inserted 执行 INSERT 操作插入的行数。
Innodb_rows_updated 执行 UPDATE 操作更新的行数。
Innodb_rows_deleted 执行 DELETE 操作删除的行数。
Connections 试图连接 MySQL 服务器的次数。
Uptime 服务器工作时间。
Slow_queries 慢查询的次数。

Com_*** : 这些参数对于所有存储引擎的表操作都会进行累计。

Innodb_*** : 这几个参数只是针对InnoDB 存储引擎的,累加的算法也略有不同。

2 定位低效率执行SQL

可以通过以下两种方式定位执行效率较低的 SQL 语句。

  • 慢查询日志 : 通过慢查询日志定位那些执行效率较低的 SQL 语句,用–log-slow-queries[=file_name]选项启动时,mysqld 写一个包含所有执行时间超过 long_query_time 秒的 SQL 语句的日志文件。具体可以查看日志管理的相关部分。
  • show processlist : 慢查询日志在查询结束以后才纪录,所以在应用反映执行效率出现问题的时候查询慢查询日志并不能定位问题,可以使用show processlist命令查看当前MySQL在进行的线程,包括线程的状态、是否锁表等,可以实时地查看 SQL 的执行情况,同时对一些锁表操作进行优化

mysql> show processlist;
+----+------+-----------+---------+---------+------+----------+------------------+
| Id | User | Host      | db      | Command | Time | State    | Info             |
+----+------+-----------+---------+---------+------+----------+------------------+
|  2 | root | localhost | demo_02 | Query   |    0 | starting | show processlist |
|  3 | root | localhost | demo_02 | Sleep   |    4 |          | NULL             |
+----+------+-----------+---------+---------+------+----------+------------------+

注意,此时ubuntu开启了两个连接。第一行的id指的是当前连接的id。然后用户名,主机名,数据库名,执行的操作。第二行的id指的是另外一个客户端。如果我们此时将另一个客户端使用数据库demo_01,则上面表中的内容也将会切换。sleep表示没有执行任何操作。

1) id列,用户登录mysql时,系统分配的"connection_id",可以使用函数connection_id()查看

2) user列,显示当前用户。如果不是root,这个命令就只显示用户权限范围的sql语句

3) host列,显示这个语句是从哪个ip的哪个端口上发的,可以用来跟踪出现问题语句的用户

4) db列,显示这个进程目前连接的是哪个数据库

5) command列,显示当前连接的执行的命令,一般取值为休眠(sleep),查询(query),连接(connect)等

6) time列,显示这个状态持续的时间,单位是秒

7) state列,显示使用当前连接的sql语句的状态,很重要的列。state描述的是语句执行中的某一个状态。一个sql语句,以查询为例,可能需要经过copying to tmp table、sorting result、sending data等状态才可以完成

8) info列,显示这个sql语句,是判断问题语句的一个重要依据

为了更好的演示慢查询的效果:
创建tb_item数据表,导入250万条数据。

CREATE TABLE `tb_item` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品id',
  `title` varchar(100) NOT NULL COMMENT '商品标题',
  `price` decimal(20,2) NOT NULL COMMENT '商品价格,单位为:元',
  `num` int(10) NOT NULL COMMENT '库存数量',
  `categoryid` bigint(10) NOT NULL COMMENT '所属类目,叶子类目',
  `status` varchar(1) DEFAULT NULL COMMENT '商品状态,1-正常,2-下架,3-删除',
  `sellerid` varchar(50) DEFAULT NULL COMMENT '商家ID',
  `createtime` datetime DEFAULT NULL COMMENT '创建时间',
  `updatetime` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品表'

存储过程

delimiter $

create procedure insert_tb_item(num int)
begin
while num <= 10000000 do
insert into tb_item values(num,concat('货物',num,'号'),round(RAND() * 100000,2),FLOOR(RAND() * 100000),FLOOR(RAND() * 10),'1','5435343235','2019-04-20 22:37:15','2019-04-20 22:37:15');
set num = num + 1;
end while;
end$

调用存储过程

call insert_tb_item(1);

我们在客户端2中开始查询,客户端3中立即开始show processlist(保证在查询结果出来之前),可以看到如下结果。
客户端2:

mysql> select count(*) from tb_item$
+----------+
| count(*) |
+----------+
|  2499695 |
+----------+
1 row in set (2.94 sec)

可以看到,查询使用了3s
客户端3:

mysql> show processlist;
+----+------+-----------+---------+---------+------+--------------+------------------------------+
| Id | User | Host      | db      | Command | Time | State        | Info                         |
+----+------+-----------+---------+---------+------+--------------+------------------------------+
|  2 | root | localhost | demo_02 | Query   |    1 | Sending data | select count(*) from tb_item |
|  3 | root | localhost | demo_02 | Query   |    0 | starting     | show processlist             |
+----+------+-----------+---------+---------+------+--------------+------------------------------+
2 rows in set (0.00 sec)

可以看到连接为2的客户端,执行了一条查询语句,输出这个processlist的时候,处于1s,当前的状态在发送数据。执行的具体的SQL语句就是count(*);
再尝试一下:

mysql> select price from tb_item where title='货物10号'$
+----------+
| price    |
+----------+
| 27202.53 |
+----------+
1 row in set (2.50 sec)

mysql> show processlist;
+----+------+-----------+---------+---------+------+--------------+-----------------------------------------------------+
| Id | User | Host      | db      | Command | Time | State        | Info                                                |
+----+------+-----------+---------+---------+------+--------------+-----------------------------------------------------+
|  2 | root | localhost | demo_02 | Query   |    1 | Sending data | select price from tb_item where title='货物10号'    |
|  3 | root | localhost | demo_02 | Query   |    0 | starting     | show processlist                                    |
+----+------+-----------+---------+---------+------+--------------+-----------------------------------------------------+
2 rows in set (0.00 sec)

通过show processlist我们就可以实时的查看到当前系统当中每一个客户端正在执行的慢查询的SQL语句

3 explain分析执行计划

通过以上步骤查询到效率低的 SQL 语句后,可以通过 EXPLAIN或者 DESC命令获取 MySQL如何执行 SELECT 语句的信息,包括在 SELECT 语句执行过程中表如何连接和连接的顺序
查询SQL语句的执行计划 :

explain  select * from tb_item where id = 1;$
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table   | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | tb_item | NULL       | const | PRIMARY       | PRIMARY | 4       | const |    1 |   100.00 | NULL  |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.06 sec)
explain  select * from tb_item where title = '阿尔卡特 (OT-979) 冰川白 联通3G手机3';

+----+-------------+---------+------------+------+---------------+------+---------+------+---------+----------+-------------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+---------+------------+------+---------------+------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | tb_item | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 2487696 |    10.00 | Using where |
+----+-------------+---------+------------+------+---------------+------+---------+------+---------+----------+-------------+
1 row in set, 1 warning (0.00 sec)
字段 含义
id select查询的序列号,是一组数字,表示的是查询中执行select子句或者是操作表的顺序。
select_type 表示 SELECT 的类型,常见的取值有 SIMPLE(简单表,即不使用表连接或者子查询)、PRIMARY(主查询,即外层的查询)、UNION(UNION 中的第二个或者后面的查询语句)、SUBQUERY(子查询中的第一个 SELECT)等
table 输出结果集的表
type 表示表的连接类型,性能由好到差的连接类型为( system —> const -----> eq_ref ------> ref -------> ref_or_null----> index_merge —> index_subquery -----> range -----> index ------> all )
possible_keys 表示查询时,可能使用的索引
key 表示实际使用的索引
key_len 索引字段的长度
rows 扫描行的数量
extra 执行情况的说明和描述

3.1 环境准备

在这里插入图片描述

CREATE TABLE `t_role` (
  `id` varchar(32) NOT NULL,
  `role_name` varchar(255) DEFAULT NULL,
  `role_code` varchar(255) DEFAULT NULL,
  `description` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_role_name` (`role_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `t_user` (
  `id` varchar(32) NOT NULL,
  `username` varchar(45) NOT NULL,
  `password` varchar(96) NOT NULL,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `unique_user_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


CREATE TABLE `user_role` (
  `id` int(11) NOT NULL auto_increment ,
  `user_id` varchar(32) DEFAULT NULL,
  `role_id` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_ur_user_id` (`user_id`),
  KEY `fk_ur_role_id` (`role_id`),
  CONSTRAINT `fk_ur_role_id` FOREIGN KEY (`role_id`) REFERENCES `t_role` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_ur_user_id` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;




insert into `t_user` (`id`, `username`, `password`, `name`) values('1','super','$2a$10$TJ4TmCdK.X4wv/tCqHW14.w70U3CC33CeVncD3SLmyMXMknstqKRe','超级管理员');
insert into `t_user` (`id`, `username`, `password`, `name`) values('2','admin','$2a$10$TJ4TmCdK.X4wv/tCqHW14.w70U3CC33CeVncD3SLmyMXMknstqKRe','系统管理员');
insert into `t_user` (`id`, `username`, `password`, `name`) values('3','itcast','$2a$10$8qmaHgUFUAmPR5pOuWhYWOr291WJYjHelUlYn07k5ELF8ZCrW0Cui','test02');
insert into `t_user` (`id`, `username`, `password`, `name`) values('4','stu1','$2a$10$pLtt2KDAFpwTWLjNsmTEi.oU1yOZyIn9XkziK/y/spH5rftCpUMZa','学生1');
insert into `t_user` (`id`, `username`, `password`, `name`) values('5','stu2','$2a$10$nxPKkYSez7uz2YQYUnwhR.z57km3yqKn3Hr/p1FR6ZKgc18u.Tvqm','学生2');
insert into `t_user` (`id`, `username`, `password`, `name`) values('6','t1','$2a$10$TJ4TmCdK.X4wv/tCqHW14.w70U3CC33CeVncD3SLmyMXMknstqKRe','老师1');



INSERT INTO `t_role` (`id`, `role_name`, `role_code`, `description`) VALUES('5','学生','student','学生');
INSERT INTO `t_role` (`id`, `role_name`, `role_code`, `description`) VALUES('7','老师','teacher','老师');
INSERT INTO `t_role` (`id`, `role_name`, `role_code`, `description`) VALUES('8','教学管理员','teachmanager','教学管理员');
INSERT INTO `t_role` (`id`, `role_name`, `role_code`, `description`) VALUES('9','管理员','admin','管理员');
INSERT INTO `t_role` (`id`, `role_name`, `role_code`, `description`) VALUES('10','超级管理员','super','超级管理员');


INSERT INTO user_role(id,user_id,role_id) VALUES(NULL, '1', '5'),(NULL, '1', '7'),(NULL, '2', '8'),(NULL, '3', '9'),(NULL, '4', '8'),(NULL, '5', '10') ;
mysql> select * from t_user;
+----+----------+--------------------------------------------------------------+-----------------+
| id | username | password                                                     | name            |
+----+----------+--------------------------------------------------------------+-----------------+
| 1  | super    | $2a$10$TJ4TmCdK.X4wv/tCqHW14.w70U3CC33CeVncD3SLmyMXMknstqKRe | 超级管理员      |
| 2  | admin    | $2a$10$TJ4TmCdK.X4wv/tCqHW14.w70U3CC33CeVncD3SLmyMXMknstqKRe | 系统管理员      |
| 3  | itcast   | $2a$10$8qmaHgUFUAmPR5pOuWhYWOr291WJYjHelUlYn07k5ELF8ZCrW0Cui | test02          |
| 4  | stu1     | $2a$10$pLtt2KDAFpwTWLjNsmTEi.oU1yOZyIn9XkziK/y/spH5rftCpUMZa | 学生1           |
| 5  | stu2     | $2a$10$nxPKkYSez7uz2YQYUnwhR.z57km3yqKn3Hr/p1FR6ZKgc18u.Tvqm | 学生2           |
| 6  | t1       | $2a$10$TJ4TmCdK.X4wv/tCqHW14.w70U3CC33CeVncD3SLmyMXMknstqKRe | 老师1           |
+----+----------+--------------------------------------------------------------+-----------------+
6 rows in set (0.01 sec)

mysql> select * from t_role;
+----+-----------------+--------------+-----------------+
| id | role_name       | role_code    | description     |
+----+-----------------+--------------+-----------------+
| 10 | 超级管理员      | super        | 超级管理员      |
| 5  | 学生            | student      | 学生            |
| 7  | 老师            | teacher      | 老师            |
| 8  | 教学管理员      | teachmanager | 教学管理员      |
| 9  | 管理员          | admin        | 管理员          |
+----+-----------------+--------------+-----------------+
5 rows in set (0.00 sec)

mysql> select * from user_role;
+----+---------+---------+
| id | user_id | role_id |
+----+---------+---------+
|  1 | 1       | 5       |
|  2 | 1       | 7       |
|  3 | 2       | 8       |
|  4 | 3       | 9       |
|  5 | 4       | 8       |
|  6 | 5       | 10      |
+----+---------+---------+
6 rows in set (0.00 sec)

3.2 explain 之 id

id 字段是 select查询的序列号,是一组数字,表示的是查询中执行select子句或者是操作表的顺序。id 情况有三种 :
(如果是单表操作,id的作用不大,如果是多表操作,这个时候通过id就可以分析出SQL语句中所关联的表的执行顺序)

1) id 相同表示加载表的顺序是从上到下。

explain select * from t_role r, t_user u, user_role ur where r.id = ur.role_id and u.id = ur.user_id ;
+----+-------------+-------+------------+--------+-----------------------------+---------------+---------+--------------------+------+----------+-------------+
| id | select_type | table | partitions | type   | possible_keys               | key           | key_len | ref                | rows | filtered | Extra       |
+----+-------------+-------+------------+--------+-----------------------------+---------------+---------+--------------------+------+----------+-------------+
|  1 | SIMPLE      | r     | NULL       | ALL    | PRIMARY                     | NULL          | NULL    | NULL               |    5 |   100.00 | NULL        |
|  1 | SIMPLE      | ur    | NULL       | ref    | fk_ur_user_id,fk_ur_role_id | fk_ur_role_id | 99      | demo_02.r.id       |    1 |   100.00 | Using where |
|  1 | SIMPLE      | u     | NULL       | eq_ref | PRIMARY                     | PRIMARY       | 98      | demo_02.ur.user_id |    1 |   100.00 | NULL        |
+----+-------------+-------+------------+--------+-----------------------------+---------------+---------+--------------------+------+----------+-------------+

这里的是多表联查,这时候id全部都是1,这时,就会在加载表的时候,从上往下加载,先加载r,然后ur,最后u。

2) id 不同id值越大,优先级越高,越先被执行。

EXPLAIN SELECT * FROM t_role WHERE id = (SELECT role_id FROM user_role WHERE user_id = (SELECT id FROM t_user WHERE username = 'stu1'))

查询过程:在内层子查询中先根据用户名查询id,拿到用户id之后,再到中间表中查询角色id,然后再到角色表中根据角色id查询角色信息,就是一个嵌套子查询。

---------+---------+-------+------+----------+-------------+
| id | select_type | table     | partitions | type  | possible_keys        | key                  | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-----------+------------+-------+----------------------+----------------------+---------+-------+------+----------+-------------+
|  1 | PRIMARY     | t_role    | NULL       | const | PRIMARY              | PRIMARY              | 98      | const |    1 |   100.00 | NULL        |
|  2 | SUBQUERY    | user_role | NULL       | ref   | fk_ur_user_id        | fk_ur_user_id        | 99      | const |    1 |   100.00 | Using where |
|  3 | SUBQUERY    | t_user    | NULL       | const | unique_user_username | unique_user_username | 137     | const |    1 |   100.00 | Using index |
+----+-------------+-----------+------------+-------+----------------------+----------------------+---------+-------+------+----------+-------------+
3 rows in set, 1 warning (0.04 sec)

这时候,先查询的是user表,然后是user_role,然后是role表。

3) id 有相同,也有不同,同时存在。id相同的可以认为是一组,从上往下顺序执行;在所有的组中,id的值越大,优先级越高,越先执行。

EXPLAIN SELECT * FROM t_role r , (SELECT * FROM user_role ur WHERE ur.`user_id` = '2') a WHERE r.id = a.role_id ; 
+----+-------------+-------+------------+--------+-----------------------------+----------                                     -----+---------+--------------------+------+----------+-------------+
| id | select_type | table | partitions | type   | possible_keys               | key                                                | key_len | ref                | rows | filtered | Extra       |
+----+-------------+-------+------------+--------+-----------------------------+----------                                     -----+---------+--------------------+------+----------+-------------+
|  1 | SIMPLE      | ur    | NULL       | ref    | fk_ur_user_id,fk_ur_role_id | fk_ur_use                                     r_id | 99      | const              |    1 |   100.00 | Using where |
|  1 | SIMPLE      | r     | NULL       | eq_ref | PRIMARY                     | PRIMARY                                            | 98      | demo_02.ur.role_id |    1 |   100.00 | NULL        |
+----+-------------+-------+------------+--------+-----------------------------+----------                                     -----+---------+--------------------+------+----------+-------------+
2 rows in set, 1 warning (0.00 sec)

控制的是表结构的执行顺序

3.3 explain 之 select_type

表示 SELECT 的类型,常见的取值,如下表所示

select_type 含义
SIMPLE 简单的select查询,查询中不包含子查询或者UNION
PRIMARY 查询中若包含任何复杂的子查询,最外层查询标记为该标识
SUBQUERY 在SELECT 或 WHERE 列表中包含了子查询
DERIVED 在FROM 列表中包含的子查询,被标记为 DERIVED(衍生) MYSQL会递归执行这些子查询,把结果放在临时表中
UNION 若第二个SELECT出现在UNION之后,则标记为UNION ; 若UNION包含在FROM子句的子查询中,外层SELECT将被标记为 : DERIVED
UNION RESULT 从UNION表获取结果的SELECT

这几种方式从上到下效率越来越低。

mysql> explain select * from t_user;
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------+
|  1 | SIMPLE      | t_user | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    6 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------+
mysql> explain select * from t_user where id=(select id from user_role where role_id='9');
+----+-------------+-----------+------------+------+---------------+---------------+---------+-------+------+----------+-------------+
| id | select_type | table     | partitions | type | possible_keys | key           | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-----------+------------+------+---------------+---------------+---------+-------+------+----------+-------------+
|  1 | PRIMARY     | t_user    | NULL       | ALL  | PRIMARY       | NULL          | NULL    | NULL  |    6 |    16.67 | Using where |
|  2 | SUBQUERY    | user_role | NULL       | ref  | fk_ur_role_id | fk_ur_role_id | 99      | const |    1 |   100.00 | Using index |
+----+-------------+-----------+------------+------+---------------+---------------+---------+-------+------+----------+-------------+
2 rows in set, 3 warnings (0.00 sec)

subquery表示子查询,当在select或者where列表当中包含了子查询,这个时候就是subquery,子查询外面的那层查询,就是primary。

注意:在高级版本中,derived可能不会显示出来

explain select a.* from (select * from t_user where id in ('1','2')) a;
+----+-------------+--------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | t_user | NULL       | range | PRIMARY       | PRIMARY | 98      | NULL |    2 |   100.00 | Using where |
+----+-------------+--------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
mysql> explain select * from t_user where id='1' union select * from t_user where id='2';
+----+--------------+------------+------------+-------+---------------+---------+---------+-------+------+----------+-----------------+
| id | select_type  | table      | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra           |
+----+--------------+------------+------------+-------+---------------+---------+---------+-------+------+----------+-----------------+
|  1 | PRIMARY      | t_user     | NULL       | const | PRIMARY       | PRIMARY | 98      | const |    1 |   100.00 | NULL            |
|  2 | UNION        | t_user     | NULL       | const | PRIMARY       | PRIMARY | 98      | const |    1 |   100.00 | NULL            |
| NULL | UNION RESULT | <union1,2> | NULL       | ALL   | NULL          | NULL    | NULL    | NULL  | NULL |     NULL | Using temporary |
+----+--------------+------------+------------+-------+---------------+---------+---------+-------+------+----------+-----------------+
3 rows in set, 1 warning (0.00 sec)

3.4 explain 之 table

展示这一行的数据是关于哪一张表的

3.5 explain 之 type

type 显示的是访问类型,是较为重要的一个指标,通过type指标能够大概的知道当前SQL语句它的耗时情况。可取值为:

type 含义
NULL MySQL不访问任何表,索引,直接返回结果
system 表只有一行记录(等于系统表),这是const类型的特例,一般不会出现
const 表示通过索引一次就找到了,const 用于比较primary key 或者 unique 索引。因为只匹配一行数据,所以很快。如将主键置于where列表中,MySQL 就能将该查询转换为一个常亮。const于将 “主键” 或 “唯一” 索引的所有部分与常量值进行比较
eq_ref 类似ref,区别在于使用的是唯一索引,使用主键的关联查询,关联查询出的记录只有一条。常见于主键或唯一索引扫描
ref 非唯一性索引扫描,返回匹配某个单独值的所有行。本质上也是一种索引访问,返回所有匹配某个单独值的所有行(多个)
range 只检索给定返回的行,使用一个索引来选择行。 where 之后出现 between , < , > , in 等操作。
index index 与 ALL的区别为 index 类型只是遍历了索引树, 通常比ALL 快, ALL 是遍历数据文件。
all 将遍历全表以找到匹配的行

结果值从最好到最坏以此是:

NULL > system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL


system > const > eq_ref > ref > range > index > ALL

一般来说, 我们需要保证查询至少达到 range 级别, 最好达到ref 。
查询当前时间,type为NULL

mysql> explain select now();
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra          |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
|  1 | SIMPLE      | NULL  | NULL       | NULL | NULL          | NULL | NULL    | NULL | NULL |     NULL | No tables used |
+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+----------------+
1 row in set, 1 warning (0.09 sec)

const通常指用唯一索引或者主键来进行查询。
主键

mysql> explain select * from t_user where id='1';
+----+-------------+--------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table  | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+--------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | t_user | NULL       | const | PRIMARY       | PRIMARY | 98      | const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

唯一索引

mysql> explain select * from t_user where username='stu1';
+----+-------------+--------+------------+-------+----------------------+----------------------+---------+-------+------+----------+-------+
| id | select_type | table  | partitions | type  | possible_keys        | key                  | key_len | ref   | rows | filtered | Extra |
+----+-------------+--------+------------+-------+----------------------+----------------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | t_user | NULL       | const | unique_user_username | unique_user_username | 137     | const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+-------+----------------------+----------------------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

eq_ref多表关联查询,通常查询出来的只有一条数据。比如我们可以让用户id关联角色id

mysql> explain select * from t_user u,t_role r where u.id=r.id;
+----+-------------+-------+------------+--------+---------------+---------+---------+--------------+------+----------+-------+
| id | select_type | table | partitions | type   | possible_keys | key     | key_len | ref          | rows | filtered | Extra |
+----+-------------+-------+------------+--------+---------------+---------+---------+--------------+------+----------+-------+
|  1 | SIMPLE      | r     | NULL       | ALL    | PRIMARY       | NULL    | NULL    | NULL         |    5 |   100.00 | NULL  |
|  1 | SIMPLE      | u     | NULL       | eq_ref | PRIMARY       | PRIMARY | 98      | demo_02.r.id |    1 |   100.00 | NULL  |
+----+-------------+-------+------------+--------+---------------+---------+---------+--------------+------+----------+-------+
2 rows in set, 1 warning (0.00 sec)

对于ref
给name添加非唯一性索引

mysql> create index idx_user on t_user(name);
Query OK, 0 rows affected (0.15 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> explain select * from t_user where name='a';
+----+-------------+--------+------------+------+---------------+----------+---------+-------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key      | key_len | ref   | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+----------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | t_user | NULL       | ref  | idx_user      | idx_user | 137     | const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+----------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

对于index的话,

mysql> explain select id from t_user;
+----+-------------+--------+------------+-------+---------------+----------------------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type  | possible_keys | key                  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+-------+---------------+----------------------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | t_user | NULL       | index | NULL          | unique_user_username | 137     | NULL |    6 |   100.00 | Using index |
+----+-------------+--------+------------+-------+---------------+----------------------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

因为id是主键,主键有所用,这里相当于我们扫描了整张表的索引。

对于all

mysql> explain select * from t_user;
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------+
|  1 | SIMPLE      | t_user | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    6 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------+
1 row in set, 1 warning (0.01 sec)

3.6 explain 之 key

possible_keys : 显示可能应用在这张表的索引, 一个或多个

key : 实际使用的索引, 如果为NULL, 则没有使用索引。

key_len : 表示索引中使用的字节数, 该值为索引字段最大可能长度,并非实际使用长度,在不损失精确性的前提下, 长度越短越好

3.7 explain 之 rows

扫描行的数量。

mysql> explain select * from t_user where name='a';
+----+-------------+--------+------------+------+---------------+----------+---------+-------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key      | key_len | ref   | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+----------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | t_user | NULL       | ref  | idx_user      | idx_user | 137     | const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+----------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

为什么只扫面了一行呢,因为我们刚才对name字段建立了索引。索引字段是生效的。

mysql> explain select * from t_user where password='a';
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | t_user | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    6 |    16.67 | Using where |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

用password来查,扫描了6行,因为数据库表中有6条记录,没有创建索引,所以扫描的是整张表结构。

3.8 explain 之 extra

其他的额外的执行计划信息,在该列展示 。

extra 含义
using filesort 说明mysql会对数据使用一个外部的索引排序,而不是按照表内的索引顺序进行读取, 称为 “文件排序”, 效率低。
using temporary 使用了临时表保存中间结果,MySQL在对查询结果排序时使用临时表。常见于 order by 和 group by; 效率低
using index 表示相应的select操作使用了覆盖索引, 避免访问表的数据行, 效率不错。

前面两个如果出现了,我们就要考虑优化了,保持的是最后一个。

mysql> explain select * from t_user order by id;
+----+-------------+--------+------------+-------+---------------+---------+---------+------+------+----------+-------+
| id | select_type | table  | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra |
+----+-------------+--------+------------+-------+---------------+---------+---------+------+------+----------+-------+
|  1 | SIMPLE      | t_user | NULL       | index | NULL          | PRIMARY | 98      | NULL |    6 |   100.00 | NULL  |
+----+-------------+--------+------------+-------+---------------+---------+---------+------+------+----------+-------+
1 row in set, 1 warning (0.03 sec)

mysql> explain select * from t_user order by password;
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+----------------+
| id | select_type | table  | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra          |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+----------------+
|  1 | SIMPLE      | t_user | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    6 |   100.00 | Using filesort |
+----+-------------+--------+------------+------+---------------+------+---------+------+------+----------+----------------+
1 row in set, 1 warning (0.00 sec)

上面使用id进行排序,是NULL,可以不管,但是使用password进行排序,出现了using filesort。这时需要扫描文件当中的内容,然后再去排序。
需要如何优化呢?我们对password建立索引就OK,因为我们对name建立了索引,所以我们看一下根据name进行排序的效果。

mysql> explain select name from t_user order by name;
+----+-------------+--------+------------+-------+---------------+----------+---------+------+------+----------+-------------+
| id | select_type | table  | partitions | type  | possible_keys | key      | key_len | ref  | rows | filtered | Extra       |
+----+-------------+--------+------------+-------+---------------+----------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | t_user | NULL       | index | NULL          | idx_user | 137     | NULL |    6 |   100.00 | Using index |
+----+-------------+--------+------------+-------+---------------+----------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

此时extra变为using index.注意,这里把前面select *改为select name.
如果使用group by的时候出现using temporary 也需要进行优化

4 show profile分析SQL

Mysql从5.0.37版本开始增加了对 show profiles 和 show profile 语句的支持。show profiles 能够在做SQL优化时帮助我们了解时间都耗费到哪里去了。

通过 have_profiling 参数,能够看到当前MySQL是否支持profile:

mysql> select @@have_profiling;
+------------------+
| @@have_profiling |
+------------------+
| YES              |
+------------------+
1 row in set, 1 warning (0.06 sec)

默认profiling是关闭的,可以通过set语句在Session级别开启profiling:

mysql> set profiling=1;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> select @@profiling;
+-------------+
| @@profiling |
+-------------+
|           1 |
+-------------+
1 row in set, 1 warning (0.01 sec)

@@profiling变量的值为1时,表示已开启,0时表示未开启。

我们可以通过show profiles可以查看到刚才所有操作的耗时。

首先,我们可以执行一系列的操作,如下图所示:

show databases;

use db01;

show tables;

select * from tb_item where id < 5;

select count(*) from tb_item;

执行完上述命令之后,再执行show profiles 指令, 来查看SQL语句执行的耗时:

mysql> show profiles;
+----------+------------+-----------------------------------------+
| Query_ID | Duration   | Query                                   |
+----------+------------+-----------------------------------------+
|        1 | 0.00018625 | select @@profiling                      |
|        2 | 0.00029275 | SELECT DATABASE()                       |
|        3 | 0.00036125 | select * from t_user                    |
|        4 | 2.84136725 | select count(*) from tb_item            |
|        5 | 2.95153675 | select * from tb_item where title='aaa' |
+----------+------------+-----------------------------------------+
5 rows in set, 1 warning (0.00 sec)

query_id查询的id,duration指的是该条SQL语句的耗时。
我们现在已经知道某条SQL语句的执行时间了,那么如何分析这些时间具体耗费在哪些阶段呢?
通过show profile for query query_id 语句可以查看到该SQL执行过程中每个线程的状态和消耗的时间:

mysql> show profile for query 5;
+----------------------+----------+
| Status               | Duration |
+----------------------+----------+
| starting             | 0.000066 |
| checking permissions | 0.000011 |
| Opening tables       | 0.000039 |
| init                 | 0.000036 |
| System lock          | 0.000012 |
| optimizing           | 0.000013 |
| statistics           | 0.000018 |
| preparing            | 0.000016 |
| executing            | 0.000006 |
| Sending data         | 2.950914 |
| end                  | 0.000017 |
| query end            | 0.000012 |
| closing tables       | 0.000011 |
| freeing items        | 0.000335 |
| cleaning up          | 0.000032 |
+----------------------+----------+
15 rows in set, 1 warning (0.00 sec)

可知时间都耗费在sending data中了,这个

TIP :
Sending data 状态表示MySQL线程开始访问数据行并把结果返回给客户端,而不仅仅是返回个客户端。由于在Sending data状态下,MySQL线程往往需要做大量的磁盘读取操作,所以经常是整各查询中耗时最长的状态。

在获取到最消耗时间的线程状态后,MySQL支持进一步选择all、cpu、block io 、context switch、page faults等明细类型类查看MySQL在使用什么资源上耗费了过高的时间。例如,选择查看CPU的耗费时间 :

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1f5l8GGG-1611300203149)(assets/1552489671119.png)]

字段 含义
Status sql 语句执行的状态
Duration sql 执行过程中每一个步骤的耗时
CPU_user 当前用户占有的cpu
CPU_system 系统占有的cpu

5 trace分析优化器执行计划

在MySQL体系结构中,服务端第二层在SQL接口和解析之后就是优化阶段了。在优化器中,我们要对SQL语句按照我们的规则进行优化处理。
MySQL5.6提供了对SQL的跟踪trace, 通过trace文件能够进一步了解为什么优化器选择A计划, 而不是选择B计划。

打开trace , 设置格式为 JSON,并设置trace最大能够使用的内存大小,避免解析过程中因为默认内存过小而不能够完整展示。

SET optimizer_trace="enabled=on",end_markers_in_json=on;
set optimizer_trace_max_mem_size=1000000;

执行SQL语句 :

select * from tb_item where id < 4;

最后, 检查information_schema.optimizer_trace就可以知道MySQL是如何执行SQL的 :

select * from information_schema.optimizer_trace\G;

猜你喜欢

转载自blog.csdn.net/qq_39736597/article/details/112978320