前言
之前文章介绍索引失效的场景(聊一聊MySQL索引失效的问题),用到了explain执行计划,执行计划返回执行过程中每一步的信息,而不是执行它。
通过返回的一行或多行信息,显示出执行计划中的每一部分和执行的次序,从而可以从分析结果中,找到查询语句或是表结构的性能瓶颈。
今天我们举一些实际的例子,来解释一下explain执行计划各字段的含义。
首先建立 用户,角色,关系,分区表。
CREATE TABLE table_user(
id INT AUTO_INCREMENT,
user VARCHAR(30),
pwd VARCHAR(30),
description VARCHAR(90),
PRIMARY KEY (id));
CREATE TABLE table_role(
id INT AUTO_INCREMENT,
name VARCHAR(30),
description VARCHAR(90),
PRIMARY KEY (id));
CREATE TABLE table_relation(
id INT AUTO_INCREMENT,
user_id INT,
role_id INT,
FOREIGN KEY (user_id) REFERENCES table_user (id),
FOREIGN KEY (role_id) REFERENCES table_role (id),
PRIMARY KEY (id));
CREATE TABLE table_partitions(
id INT AUTO_INCREMENT,
name VARCHAR(30),
age INT,
address VARCHAR(30),
PRIMARY KEY (id))PARTITION BY HASH(id) PARTITIONS 2;
插入一些数据。
insert into table_user(user,pwd,description) value('tony','abc123','admin');
insert into table_user(user,pwd,description) value('tom','123456','general user');
insert into table_user(user,pwd,description) value('jerry','123456','general user');
insert into table_role(name,description) value('admin','admin role');
insert into table_role(name,description) value('general','general role');
insert into table_relation(user_id,role_id) value(1,1);
insert into table_relation(user_id,role_id) value(2,2);
insert into table_relation(user_id,role_id) value(3,2);
insert into table_partitions(name,age,address) value('wang',21,'shenzhen');
insert into table_partitions(name,age,address) value('zhang',23,'shanghai');
insert into table_partitions(name,age,address) value('li',26,'beijing');
创建索引。
CREATE INDEX index_age ON table_partitions(age);
CREATE INDEX index_name_age ON table_partitions(name,age);
一、id字段
select查询的序列号,表示的是查询中执行select子句或者是操作表的顺序,id值越大优先级越高,越先被执行。
explain select * from table_role,table_user; #因为排版问题,去掉了一些信息
+----+-------------+------------+------------+------+---------------+------+
| id | select_type | table | partitions | type | possible_keys | key |
+----+-------------+------------+------------+------+---------------+------+
| 1 | SIMPLE | table_role | NULL | ALL | NULL | NULL |
| 1 | SIMPLE | table_user | NULL | ALL | NULL | NULL |
+----+-------------+------------+------------+------+---------------+------+
explain select * from table_relation where role_id=(select id from table_role where name='admin');
+----+-------------+----------------+------------+------+---------------+---------+
| id | select_type | table | partitions | type | possible_keys | key |
+----+-------------+----------------+------------+------+---------------+---------+
| 1 | PRIMARY | table_relation | NULL | ref | role_id | role_id |
| 2 | SUBQUERY