如何分析mysql中Explain的执行结果1

139 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情

先附上官网文档说明的地址,更深入的大家自行查阅:dev.mysql.com/doc/refman/…

建表示例

CREATE TABLE `test_author` (
  `id` int(11) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `utime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='作者表';
 
insert into test_author(id,name) values(1,'牛仔');
insert into test_author(id,name) values(2,'小海豚');
 
CREATE TABLE `test_book` (
  `id` int(11) NOT NULL,
  `name` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `common_index` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='出版书籍表';
 
insert into test_book(id,name)values(1,'西游记');
insert into test_book(id,name)values(2,'葫芦娃');
 
CREATE TABLE `author_id` (
  `id` int(11) NOT NULL,
  `author_id` int(11) DEFAULT NULL,
  `book_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `union_author_book` (`author_id`,`book_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
insert into test_author_book values(1,1,1),(2,1,2);

使用方式

在我们正常的sql语句前面添加参数 explain image.png

Explain列说明

id

SQL语句总有几个sql语句就会有几个id编号,编号值越高,执行越早。如果id为空,则最后执行。

select_type

表示该语句是简单查询还是复杂查询。大体常用的有如下几种:

simple

简单查询,该查询不包含子查询和union。例如:

explain select * from test_author where id = 1; 

primary

复杂查询中最外层的select。

subquery

select语句作为属性列的查询(非from之后的)

derived

from之后的表是由select语句产生的。

示例primary、subquery、derived

(未关闭对衍生表的合并优化前:) image.png

(关闭对衍生表的合并优化后:set session optimizer_switch=‘derived_merge=off’😉 image.png

union

union之后的所有select语句。例如: image.png

table

表示用的表是哪一个。 当from语句中有子查询时,名字可能是,其中N为id所对应行的表。 当有union时,名字可能是<union1,2>代表,id为1,2对应行的select。

partions

SQL所属的分区是哪一个。

type

SQL执行过程中有无用到索引。其值以及执行优先级为: null>system>const>eq_ref>ref>range>index>all 我们优化一般都是尽量向range靠拢,最好达到ref。

null

执行效率最高的。可以理解表都不用查。例如:

select max(id),min(id) from test_book;

在一个排好序的二叉树里面,最大,最小我们只需要获取开头或者结尾的数值即可。