EXPLAIN 是什么
MySQL 提供了一个 EXPLAIN 命令, 它可以对 SQL 语句进行分析, 并输出 SQL 执行的详细信息, 以供开发人员针对性优化.
EXPLAIN 结果中的type字段
完整的访问方法如下:
system
,
const
,
eq_ref
,
ref
,
fulltext
,
ref_or_null
,
index_merge
,
unique_subquery
,
index_subquery
,
range
,
index
,
ALL
。
- system:系统表,少量数据,往往不需要进行磁盘IO
- const:常量连接
- eq_ref:主键索引(primary key)或者非空唯一索引(unique not null)等值扫描
- ref:非主键非唯一索引等值扫描
- range:范围扫描
- index:索引树扫描 ALL:全表扫描(full table scan)
小结:
结果值从最好到最坏依次是:
system > const > eq_ref > ref
> fulltext > ref_or_null > index_merge >
unique_subquery > index_subquery >
range > index > ALL
其中比较重要的几个提取出来(见上图中的蓝
色)
SQL
性能优化的目标:至少要达到
range
级别,要求是
ref
级别,最好是
consts
级别。
(阿里巴巴
开发手册要求)