explain命令Extra字段及优化详解

本文详细解析了MySQL中的explain命令Extra字段,包括using filesort、using temporary、using index、using where和impossible where,阐述了它们在SQL执行过程中的作用,以及如何根据这些信息优化SQL性能。例如,using filesort表示额外的排序操作,using temporary表示使用了临时表,using index意味着索引覆盖,using where表示需要回表查询,而impossible where则表明where条件永远为假。
摘要由CSDN通过智能技术生成

前提:本文所有的案例均在MySQL5.7版本下实践

使用explain命令查看SQL语句的执行情况,可以帮助开发人员更快地定位到SQL执行效率欠佳的原因,本文对explain命令Extra字段的常见取值进行详解

SQL执行

SQL的编写过程是这样的:

select  dinstinct  from  join  on  where  group by  having   order by   limit

而SQL的解析过程的顺序是这样的:

from  on  join  where  group by  having  select  dinstinct  order by  limit

 

创建一张test02表,给表中的字段加上单值索引

create table test02
(
	a1 char(3),
	a2 char(3),
	a3 char(3),
	index idx_a1(a1),
	index idx_a2(a2),
	index idx_a3(a3)
);

1、using filesort

如果在Extra字段中出现了using filesort,说明SQL性能消耗大,它表示需要额外的一次排序或查询,常见于order by语句中

执行SQL,根据a1查询,然后根据a1排序,发现并没有出现using filesort

explain select * from test02 where a1 ='' order by a1 ;

+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-------+
| id | select_type | table  | partitions | type | possible_keys | key    | key_len | ref   | rows | filtered | Extra |
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | test02 | NULL       | ref  | idx_a1        | idx_a1 | 10      | const |    1 |   100.00 | NULL  |
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.01 sec)

更改SQL,根据a1查询,然后根据a2排序,出现了using filesort,这是为什么呢?

原因:查看SQL的解析顺序,先执行where子句,当查询完后,再执行order by子句,发现需要通过a2字段来进行排序,所以需要额外的一次查找或者称之为额外的一次排序,所以会出现using filesort

explain select * from test02 where a1 ='' order by a2 ;

+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+---------------------------------------+
| id | select_type | table  | partitions | type | possible_keys | key    | key_len | ref   | rows | filtered | Extra                                 |
+----+-------------+--------+------------+------+---------------+--------+---------+-------+------+----------+---------------------------------------+
|  1 | SIMPLE      | test02 | NULL 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值