前言
explain
是分析 sql 查询性能的关键工具,能帮助你理解查询的执行计划,并优化查询性能。以下是一份详细的数据库 explain
使用教程,适用于常见的数据库系统(如 mysql、postgresql 等)
1. 什么是 explain?
explain
是一个数据库命令,用于显示 sql 查询的执行计划(即数据库如何执行你的查询)。通过分析输出结果,你可以:
- 确定查询是否使用了索引。
- 发现全表扫描等低效操作。
- 优化 join 顺序或子查询。
- 估算查询的代价(如扫描的行数)。
2. 基本语法
mysql
explain [format=json|tree|traditional] select ...; -- 示例 explain select * from users where age > 30;
postgresql
explain [analyze] [verbose] select ...; -- 示例 explain analyze select * from users where age > 30;
analyze
:实际执行查询并显示详细统计信息。verbose
:显示额外的信息(如列名)。
3. explain 输出列详解(mysql)
以下是一个典型的 explain
输出结果及字段解释:
列名 | 说明 |
---|---|
id | 查询的标识符(多表 join 时,相同 id 表示同一执行层级)。 |
select_type | 查询类型(如 simple , primary , subquery , derived 等)。 |
table | 访问的表名。 |
partitions | 匹配的分区(如果表有分区)。 |
type | 关键字段:访问类型(性能从优到差排序:system > const > eq_ref > ref > range > index > all )。 |
possible_keys | 可能使用的索引。 |
key | 实际使用的索引。 |
key_len | 使用的索引长度(字节数)。 |
ref | 与索引比较的列或常量。 |
rows | 关键字段:预估需要扫描的行数。 |
filtered | 过滤后剩余行的百分比(mysql 特有)。 |
extra | 关键字段:附加信息(如 using where , using index , using temporary 等)。 |
4. 关键字段解析与优化思路
type 列
- const:通过主键或唯一索引查询,最多返回一行(最优)。
- eq_ref:join 时使用主键或唯一索引。
- ref:使用非唯一索引查找。
- range:索引范围扫描(如
between
,>
)。 - index:全索引扫描(比全表扫描稍好)。
- all:全表扫描(需优化,考虑添加索引)。
extra 列
- using where:服务器在存储引擎检索后再次过滤。
- using index:查询仅通过索引完成(覆盖索引)。
- using temporary:使用了临时表(常见于排序或分组)。
- using filesort:需要额外排序(考虑添加索引优化排序)。
rows 列
- 数值越小越好,表示预估扫描的行数。
5. 实战示例
示例表结构
create table users ( id int primary key, name varchar(50), age int, index idx_age (age) );
查询 1:未使用索引
explain select * from users where name = 'alice';
输出分析:
- type:
all
(全表扫描) - possible_keys:
null
(无可用索引) - 优化建议:为
name
列添加索引。
查询 2:使用索引
explain select * from users where age = 25;
输出分析:
- type:
ref
- key:
idx_age
- rows: 1(高效查询)
6. postgresql 的 explain 差异
- 输出格式:更详细,包含实际执行时间(需使用
explain analyze
)。 - 关键信息:
- seq scan:全表扫描。
- index scan:索引扫描。
- hash join / nested loop:join 类型。
- 示例:
explain analyze select * from users where age > 30;
7. 常见问题与优化建议
问题 1:全表扫描(type=all)
- 优化方法:为 where 条件或 join 字段添加索引。
问题 2:临时表(using temporary)
- 优化方法:优化 group by / order by 子句,确保使用索引。
问题 3:文件排序(using filesort)
- 优化方法:为 order by 字段添加索引。
问题 4:索引未生效
- 可能原因:数据类型不匹配、函数操作(如
where year(date) = 2023
)。 - 优化方法:避免在索引列上使用函数。
总结
通过 explain
分析 sql 执行计划,可以快速定位性能瓶颈。重点关注 type
、rows
和 extra
列,优先优化全表扫描、临时表和文件排序等问题。不同数据库的 explain
输出略有差异,但核心思路一致。
到此这篇关于数据库中如何使用explain分析sql执行计划的文章就介绍到这了,更多相关explain分析sql执行计划内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论