&emsp?Mysql的执行计划有12个字段,不仅是面试高频问题,也是工作中经常用到的。
id
??id是查询的主键,或者叫序列号,因为这个值是递增的。需要注意的地方就是union这个id会是null,我举个例子:
explain select id,name from student union select id,name from teacher;
??结果如下: 
select_type
??Select type有12种类型,这个确实比较繁琐啊。只能一个个解释了:
SIMPLE
??表示没有使用union和子查询。我举个例子,Join查询的结果就是SIMPLE:
explain select t.name,s.score from student t join score s on t.id = s.student_id;
??结果: 
PRIMARY
??最外部的查询,这个就不多说了。前面也有例子。
UNION
??Union的第二张表,这个也不多说了,前面也有例子。
DEPENDENT UNION
??这里我举个不恰当的例子,因为我的SQL逻辑不对,哈哈,如下:
explain
select id, name
from student t
where t.id in (
select id
from student
union
select id
from teacher);
??结果中就有了DEPENDENT UNION,如图: 
UNION RESULT
??前面说过,这里也不说了。
SUBQUERY
??举个例子,查询成绩大于平均分的记录,SQL如下:
explain select * from score s where s.score > (select avg(score) from score)
??执行计划结果: 
DEPENDENT SUBQUERY
??依赖外部查询的子查询,我举个例子:
explain select id,name, (select max(score) from score where student_id = t.id) from student t;
??结果为: 
DERIVED
??DERIVED,意思是派生表。派生表就是临时表,我举个例子,求学生的平均分,这个是个常见的需求。SQL如下:
explain
select *
from (
select avg(s.score), s.student_id
from score s
group by s.student_id) a
join student t on t.id = a.student_id;
??其中的平均分表就是派生表,执行计划如下: 
DEPENDENT DERIVED
??意思是依赖主查询的派生表。例子不好找,先省略。
MATERIALIZED
??例子不好找,先省略。
UNCACHEABLE SUBQUERY
??例子不好找,先省略。
UNCACHEABLE UNION
??例子不好找,先省略。
table
??是查询遇到的表名,一般是显示别名,少数情况下会显示union,derived,subquery开头的表名。
partitions
??查询数据使用的分区,如果数据库没分区,那么这个字段就是NULL。
type
??type是join连接的类型,这是执行计划最重要的字段,分12种,我的妈,又是12。
system
??只有一行的情况,但必须是系统表。
const
??根据主键只查一行就是这种场景,如:
explain select * from class where id = 1;
??结果为
eq_ref
?emsp;两表之间使用等于号连接,键都是非空唯一索引。我举个例子,在学生成绩表里,加上了学生的外键,然后查虽有学生语文课(ID=1)的成绩:
explain select * from student t,score s where s.student_id = t.id and s.subject_id = 1;
??结果就出现了eq_ref: 
ref
??在索引键不是唯一的情况下,类型为ref,如:
explain select * from score where student_id = 1;
??结果为ref: 
full_text
ref_or_null
index_merge
unique_subquery
index_subquery
range
??range是在索引树上按范围查找,当在索引上使用大于小于,is null, in等查询的时候,就是用到了range。这里有两个细节,一个是NULL-safe equal,也就是<=>运算符,是null比较时安全的相等运算符,二是is null也命中了索引,在一些面经里,说is null没有命中索引是不对的。举个例子:
explain select * from score where student_id between 1 and 100;
??结果就是range: 
index
??虽然名字叫索引,但是大部分情况下实际表现和ALL差不多。
ALL
??这是性能最低下的方式了。
possible_keys
??因为MySQL有查询优化器,查询优化器会生成几种SQL优化方案,然后选择一种方案。所以这里显示的是可能使用的索引。
key
??实际选择的索引,在众多优化方案里实际选择的索引。
key_len
??使用的索引长度。
ref
??用来和索引比较的列或者常量。这个值有时候可能是func。
rows
??大致需要扫描多少行数据。
filtered
??表示过滤了多少百分比的数据,100表示扫描所有行,数字越小扫描范围越小。
Extra
??这个字段超级复杂。我会另外写一篇笔记记录。
|