explain(执行计划)工具使用

主要用于分析sql语句的执行情况(并不执行sql语句)得到sql语句是否使用了索引,使用了哪些索引

语法:explain sql语句G 或 desc sql语句G

在mysql之前的版本中,explain只支持select语句,但是在最新的5.6版本中,它支持 explain update/delete了。

做实验创建两张表:

# 创建一个用户表:
create table user(
    id int primary key auto_increment,
    name varchar(32) not null default '',
    age tinyint unsigned not null default 0,
    email varchar(32) not null default '',
    classid int not null default 1
)engine myisam charset utf8;

insert into user values(null,'xiaogang',12,'gang@sohu.com',4),
(null,'xiaohong',13,'hong@sohu.com',2),
(null,'xiaolong',31,'long@sohu.com',2),
(null,'xiaofeng',22,'feng@sohu.com',3),
(null,'xiaogui',42,'gui@sohu.com',3);

# 创建一个班级表:
create table class(
    id int not null default 0,
    classname varchar(32) not null default ''
)engine myisam charset utf8;

insert into class values(1,'java'),(2,'.net'),(3,'php'),(4,'c++'),(5,'ios');

一、语法分析

explain sql语句;

返回结果分析:

名称 含义
select_type 表示查询的类型,此处是一个简单的查询
table 表示要查询的表。
type

是指查询的方式,非常重要,是分析“查数据过程”的重要依据。

可能的值:all  index  range  ref  const

possible_key

可能用到的索引

注意:系统估计可能用的几个索引,但最终,只能用1个。

key 最终用的索引。
key_len 使用的索引的最大长度。
rows 是指估计要扫描多少行。
extra

using index :是指用到了索引覆盖,效率非常高 

using where:是指光靠索引定位不了,还得where判断一下。 

using temporary:是指用上了临时表,group by 与order by不同列时,或grop by,order by 别的表的列。 

using filesort:文件排序(文件可能在磁盘,也可能在内存)

二、分析type列的值

分析
all 是扫描所有的数据行,性能最差,一般是没有添加索引,或没有使用到索引。
index

比all性能稍好一点,是指要扫描所有的索引节点。

出现index, 则说明只在索引文件中查找。

1. 索引覆盖的查询情况下,能利用上索引,但是又必须全索引扫描。

2. 是利用索引来排序,但只能取出索引的列。

range 意思是查询时,能根据索引做范围扫描。
ref 是指通过索引列,可以直接引用到某些数据行。

const

system

null

这3个分别指查询优化到常量级别,甚至不需要查找时间。

一般按照主键来查询时,易出现 const,system

或者直接查询某个表达式,不经过表时,出现null.

原文地址:https://www.cnblogs.com/chenjiacheng/p/6522256.html