2.mysql explain命令详解

EXPLAIN详解

SQL编写和解析

编写过程
	select…distinct…from…join…on…where…group by…having…order by…limit…
解析过程
	from…on…join…where…group by…having…select distinct…order by…limit…

执行计划:

mysql> explain select * from study s left join course c on c.age = s.snum where s.snum >50;
+----+-------------+-------+------------+------+---------------+-------+---------+-------------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key   | key_len | ref         | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+-------+---------+-------------+------+----------+-------------+
|  1 | SIMPLE      | s     | NULL       | ALL  | NULL          | NULL  | NULL    | NULL        | 2000 |    33.33 | Using where |
|  1 | SIMPLE      | c     | NULL       | ref  | i_age         | i_age | 5       | mydb.s.snum |  494 |   100.00 | NULL        |
+----+-------------+-------+------------+------+---------------+-------+---------+-------------+------+----------+-------------+

1、id

  • id值相同,执行顺序由上至下;
  • id值不同,优先执行值较大的查询(本质:在嵌套子查询时,先查内层,再查外层)

2、select type

primary
	包含子查询SQL中的主查询(最外层)
subquery
	包含子查询SQL中的子查询(非最外层)
simple
	简单查询(不包含子查询、union)
derived
	衍生查询
		a、在from子查询中中有一张表
		b、在from子查询中,如果有table1 union table2,则table1就是derived

3、table

  • 查询使用的表

4、type(查询效率从上至下递减)

system
	只有一条数据的系统表或衍生表只有一条数据的主查询
const
	仅能查到一条数据的SQL,用于Primary key 或unique index
eq_ref
	唯一性索引:对于每个索引键的查询,返回匹配唯一行的数据(有且只有1个,不能多,不能0),常见于primary key 和 unique key
ref
	非唯一性索引,对于每个索引键的查询,返回匹配的所有行(0,多)
range
	检索指定范围的行,where后面时一个范围查询(between,< >=,in有时候会失效,转为无索引查询)
index
	扫描索引中的全部数据
all
	扫描全表数据

5、ref

  • 指明当前表所参照的字段

6、key_len

索引长度,常用于判断复合索引是否被完全使用:
a、在utf8中,1个字符占3个字节,char(20)使用60字节;  
b、如果索引字段可以为null,会用1个字节用于标识;  
c、用两个字节标识可变长度, varchar(20) 使用62字节

7、possible keys

  • 可能用到的索引

8、key

  • 实际使用的索引

9、rows

  • 实际通过索引查询的数据个数

10、extra

  • using filesort
    order by 使用了文件排序
  • using temporary
    group by 使用了临时表
  • using where
    回表查询
  • using index
    使用了索引覆盖
  • impossible where
    不可能实现的where查询
  • using join buffer
    mysql使用了连接缓存
  • block nested-loop join
    使用了块嵌套循环
原文地址:https://www.cnblogs.com/unsigned1995/p/14153886.html