mysql explain

本文详细介绍MySQL EXPLAIN命令的两种用法及其输出结果的各列含义,包括select_type、type和extra列的具体解释,并通过实例展示不同场景下的EXPLAIN输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

explain语法
有两种用法:
  • 1.EXPLAIN tbl_name
  • 2.EXPLAIN [EXTENDED] SELECT select_options
为了更好的说明它,我们需要建两张表,下面的语句用于创建一张测试用的订单表:
  • CREATE TABLE `t_order` (
  • `order_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '订单ID',
  • `express_type` tinyint(1) unsigned NOT NULL COMMENT '快递方式',
  • `user_id` int(10) unsigned DEFAULT NULL COMMENT '用户ID',
  • `add_time` int(10) NOT NULL COMMENT '下单时间',
  • PRIMARY KEY (`order_id`),
  • KEY `user_id` (`user_id`),
  • KEY `express_type` (`express_type`)
  • ) ENGINE=InnoDB AUTO_INCREMENT=100000 DEFAULT CHARSET=utf8 COMMENT='订单记录表'
然后我往其中插入了100000条记录。
下面是订单的扩展表,仅向其中插入了一条记录,关联某笔订单。
  • CREATE TABLE `t_order_ext` (
  • `order_id` int(10) NOT NULL COMMENT '订单ID',
  • `user_type` int(11) NOT NULL DEFAULT '0' COMMENT '用户类型',
  • `comment` varchar(255) CHARACTER SET utf8 NOT NULL COMMENT '订单备注',
  • KEY `order_id` (`order_id`)
  • ) ENGINE=InnoDB DEFAULT CHARSET=utf8
先看一下第一种用法:
  • mysql> explain t_order;
  • +----------+------------------+------+-----+---------+----------------+
  • | Field    | Type             | Null | Key | Default | Extra          |
  • +----------+------------------+------+-----+---------+----------------+
  • | order_id | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
  • | add_time | int(10)          | NO   |     | NULL    |                |
  • +----------+------------------+------+-----+---------+----------------+
  • 2 rows in set (0.04 sec)
这其实和describe是等价的:
  • mysql> describe t_order;
  • +----------+------------------+------+-----+---------+----------------+
  • | Field    | Type             | Null | Key | Default | Extra          |
  • +----------+------------------+------+-----+---------+----------------+
  • | order_id | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
  • | add_time | int(10)          | NO   |     | NULL    |                |
  • +----------+------------------+------+-----+---------+----------------+
  • 2 rows in set (0.00 sec)
这返回的是表的结构,没有什么可说的。
重点是第二种用法,需要深入的了解。
先看一个例子:
  • mysql> explain select * from t_order;
  • +----+-------------+---------+------+---------------+------+---------+------+--------+-------+
  • | id | select_type | table   | type | possible_keys | key  | key_len | ref  | rows   | Extra |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+-------+
  • |  1 | SIMPLE      | t_order | ALL  | NULL          | NULL | NULL    | NULL | 100453 |       |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+-------+
  • 1 row in set (0.03 sec)
加上extended后之后:
  • mysql> explain extended select * from t_order;
  • +----+-------------+---------+------+---------------+------+---------+------+--------+----------+-------+
  • | id | select_type | table   | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+----------+-------+
  • |  1 | SIMPLE      | t_order | ALL  | NULL          | NULL | NULL    | NULL | 100453 |   100.00 |       |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+----------+-------+
  • 1 row in set, 1 warning (0.00 sec)
有必要解释一下这个长长的表格里每一列的含义:
idSELECT识别符。这是SELECT的查询序列号
select_typeSELECT类型,可以为以下任何一种:
  • SIMPLE:简单SELECT(不使用UNION或子查询)
  • PRIMARY:最外面的SELECT
  • UNION:UNION中的第二个或后面的SELECT语句
  • DEPENDENT UNION:UNION中的第二个或后面的SELECT语句,取决于外面的查询
  • UNION RESULT:UNION 的结果
  • SUBQUERY:子查询中的第一个SELECT
  • DEPENDENT SUBQUERY:子查询中的第一个SELECT,取决于外面的查询
  • DERIVED:导出表的SELECT(FROM子句的子查询)
table输出的行所引用的表
type联接类型。下面给出各种联接类型,按照从最佳类型到最坏类型进行排序:
  • system:表仅有一行(=系统表)。这是const联接类型的一个特例。
  • const:表最多有一个匹配行,它将在查询开始时被读取。因为仅有一行,在这行的列值可被优化器剩余部分认为是常数。const表很快,因为它们只读取一次!
  • eq_ref:对于每个来自于前面的表的行组合,从该表中读取一行。这可能是最好的联接类型,除了const类型。
  • ref:对于每个来自于前面的表的行组合,所有有匹配索引值的行将从这张表中读取。
  • ref_or_null:该联接类型如同ref,但是添加了MySQL可以专门搜索包含NULL值的行。
  • index_merge:该联接类型表示使用了索引合并优化方法。
  • unique_subquery:该类型替换了下面形式的IN子查询的ref: value IN (SELECT primary_key FROM single_table WHERE some_expr) unique_subquery是一个索引查找函数,可以完全替换子查询,效率更高。
  • index_subquery:该联接类型类似于unique_subquery。可以替换IN子查询,但只适合下列形式的子查询中的非唯一索引: value IN (SELECT key_column FROM single_table WHERE some_expr)
  • range:只检索给定范围的行,使用一个索引来选择行。
  • index:该联接类型与ALL相同,除了只有索引树被扫描。这通常比ALL快,因为索引文件通常比数据文件小。
  • ALL:对于每个来自于先前的表的行组合,进行完整的表扫描。
possible_keys指出MySQL能使用哪个索引在该表中找到行
key显示MySQL实际决定使用的键(索引)。如果没有选择索引,键是NULL。
key_len显示MySQL决定使用的键长度。如果键是NULL,则长度为NULL。
ref显示使用哪个列或常数与key一起从表中选择行。
rows显示MySQL认为它执行查询时必须检查的行数。多行之间的数据相乘可以估算要处理的行数。
filtered显示了通过条件过滤出的行数的百分比估计值。
Extra该列包含MySQL解决查询的详细信息
  • Distinct:MySQL发现第1个匹配行后,停止为当前的行组合搜索更多的行。
  • Not exists:MySQL能够对查询进行LEFT JOIN优化,发现1个匹配LEFT JOIN标准的行后,不再为前面的的行组合在该表内检查更多的行。
  • range checked for each record (index map: #):MySQL没有发现好的可以使用的索引,但发现如果来自前面的表的列值已知,可能部分索引可以使用。
  • Using filesort:MySQL需要额外的一次传递,以找出如何按排序顺序检索行。
  • Using index:从只使用索引树中的信息而不需要进一步搜索读取实际的行来检索表中的列信息。
  • Using temporary:为了解决查询,MySQL需要创建一个临时表来容纳结果。
  • Using where:WHERE 子句用于限制哪一个行匹配下一个表或发送到客户。
  • Using sort_union(...), Using union(...), Using intersect(...):这些函数说明如何为index_merge联接类型合并索引扫描。
  • Using index for group-by:类似于访问表的Using index方式,Using index for group-by表示MySQL发现了一个索引,可以用来查 询GROUP BY或DISTINCT查询的所有列,而不要额外搜索硬盘访问实际的表。

一.select_type的说明
1.UNION:
当通过union来连接多个查询结果时,第二个之后的select其select_type为UNION。
  • mysql> explain select * from t_order where order_id=100 union select * from t_order where order_id=200;
  • +----+--------------+------------+-------+---------------+---------+---------+-------+------+-------+
  • | id | select_type  | table      | type  | possible_keys | key     | key_len | ref   | rows | Extra |
  • +----+--------------+------------+-------+---------------+---------+---------+-------+------+-------+
  • |  1 | PRIMARY      | t_order    | const | PRIMARY       | PRIMARY | 4       | const |    1 |       |
  • |  2 | UNION        | t_order    | const | PRIMARY       | PRIMARY | 4       | const |    1 |       |
  • | NULL | UNION RESULT | <union1,2> | ALL   | NULL          | NULL    | NULL    | NULL  | NULL |       |
  • +----+--------------+------------+-------+---------------+---------+---------+-------+------+-------+
  • 3 rows in set (0.34 sec)
2.DEPENDENT UNION与DEPENDENT SUBQUERY:
当union作为子查询时,其中第二个union的select_type就是DEPENDENT UNION。
第一个子查询的select_type则是DEPENDENT SUBQUERY。
  • mysql> explain select * from t_order where order_id in (select order_id from t_order where order_id=100 union select order_id from t_order where order_id=200);
  • +----+--------------------+------------+-------+---------------+---------+---------+-------+--------+-------------+
  • | id | select_type        | table      | type  | possible_keys | key     | key_len | ref   | rows   | Extra       |
  • +----+--------------------+------------+-------+---------------+---------+---------+-------+--------+-------------+
  • |  1 | PRIMARY            | t_order    | ALL   | NULL          | NULL    | NULL    | NULL  | 100453 | Using where |
  • |  2 | DEPENDENT SUBQUERY | t_order    | const | PRIMARY       | PRIMARY | 4       | const |      1 | Using index |
  • |  3 | DEPENDENT UNION    | t_order    | const | PRIMARY       | PRIMARY | 4       | const |      1 | Using index |
  • | NULL | UNION RESULT       | <union2,3> | ALL   | NULL          | NULL    | NULL    | NULL  |   NULL |             |
  • +----+--------------------+------------+-------+---------------+---------+---------+-------+--------+-------------+
  • 4 rows in set (0.03 sec)
3.SUBQUERY:
子查询中的第一个select其select_type为SUBQUERY。
  • mysql> explain select * from t_order where order_id=(select order_id from t_order where order_id=100);
  • +----+-------------+---------+-------+---------------+---------+---------+-------+------+-------------+
  • | id | select_type | table   | type  | possible_keys | key     | key_len | ref   | rows | Extra       |
  • +----+-------------+---------+-------+---------------+---------+---------+-------+------+-------------+
  • |  1 | PRIMARY     | t_order | const | PRIMARY       | PRIMARY | 4       | const |    1 |             |
  • |  2 | SUBQUERY    | t_order | const | PRIMARY       | PRIMARY | 4       |       |    1 | Using index |
  • +----+-------------+---------+-------+---------------+---------+---------+-------+------+-------------+
  • 2 rows in set (0.03 sec)
4.DERIVED:
当子查询是from子句时,其select_type为DERIVED。
  • mysql> explain select * from (select order_id from t_order where order_id=100) a;
  • +----+-------------+------------+--------+---------------+---------+---------+------+------+-------------+
  • | id | select_type | table      | type   | possible_keys | key     | key_len | ref  | rows | Extra       |
  • +----+-------------+------------+--------+---------------+---------+---------+------+------+-------------+
  • |  1 | PRIMARY     | <derived2> | system | NULL          | NULL    | NULL    | NULL |    1 |             |
  • |  2 | DERIVED     | t_order    | const  | PRIMARY       | PRIMARY | 4       |      |    1 | Using index |
  • +----+-------------+------------+--------+---------------+---------+---------+------+------+-------------+
  • 2 rows in set (0.03 sec)
二.type的说明
1.system,const
见上面4.DERIVED的例子。其中第一行的type就是为system,第二行是const,这两种联接类型是最快的。
2.eq_ref
在t_order表中的order_id是主键,t_order_ext表中的order_id也是主键,该表可以认为是订单表的补充信息表,他们的关系是1对1,在下面的例子中可以看到b表的连接类型是eq_ref,这是极快的联接类型。
  • mysql> explain select * from t_order a,t_order_ext b where a.order_id=b.order_id;
  • +----+-------------+-------+--------+---------------+---------+---------+-----------------+------+-------------+
  • | id | select_type | table | type   | possible_keys | key     | key_len | ref             | rows | Extra       |
  • +----+-------------+-------+--------+---------------+---------+---------+-----------------+------+-------------+
  • |  1 | SIMPLE      | b     | ALL    | order_id      | NULL    | NULL    | NULL            |    1 |             |
  • |  1 | SIMPLE      | a     | eq_ref | PRIMARY       | PRIMARY | 4       | test.b.order_id |    1 | Using where |
  • +----+-------------+-------+--------+---------------+---------+---------+-----------------+------+-------------+
  • 2 rows in set (0.00 sec)
3.ref
下面的例子在上面的例子上略作了修改,加上了条件。此时b表的联接类型变成了ref。因为所有与a表中order_id=100的匹配记录都将会从b表获取。这是比较常见的联接类型。
  • mysql> explain select * from t_order a,t_order_ext b where a.order_id=b.order_id and a.order_id=100;
  • +----+-------------+-------+-------+---------------+----------+---------+-------+------+-------+
  • | id | select_type | table | type  | possible_keys | key      | key_len | ref   | rows | Extra |
  • +----+-------------+-------+-------+---------------+----------+---------+-------+------+-------+
  • |  1 | SIMPLE      | a     | const | PRIMARY       | PRIMARY  | 4       | const |    1 |       |
  • |  1 | SIMPLE      | b     | ref   | order_id      | order_id | 4       | const |    1 |       |
  • +----+-------------+-------+-------+---------------+----------+---------+-------+------+-------+
  • 2 rows in set (0.00 sec)
4.ref_or_null
user_id字段是一个可以为空的字段,并对该字段创建了一个索引。在下面的查询中可以看到联接类型为ref_or_null,这是mysql为含有null的字段专门做的处理。在我们的表设计中应当尽量避免索引字段为NULL,因为这会额外的耗费mysql的处理时间来做优化。
  • mysql> explain select * from t_order where user_id=100 or user_id is null;
  • +----+-------------+---------+-------------+---------------+---------+---------+-------+-------+-------------+
  • | id | select_type | table   | type        | possible_keys | key     | key_len | ref   | rows  | Extra       |
  • +----+-------------+---------+-------------+---------------+---------+---------+-------+-------+-------------+
  • |  1 | SIMPLE      | t_order | ref_or_null | user_id       | user_id | 5       | const | 50325 | Using where |
  • +----+-------------+---------+-------------+---------------+---------+---------+-------+-------+-------------+
  • 1 row in set (0.00 sec)
5.index_merge
经常出现在使用一张表中的多个索引时。mysql会将多个索引合并在一起,如下例:
  • mysql> explain select * from t_order where order_id=100 or user_id=10;
  • +----+-------------+---------+-------------+-----------------+-----------------+---------+------+------+-------------------------------------------+
  • | id | select_type | table   | type        | possible_keys   | key             | key_len | ref  | rows | Extra                                     |
  • +----+-------------+---------+-------------+-----------------+-----------------+---------+------+------+-------------------------------------------+
  • |  1 | SIMPLE      | t_order | index_merge | PRIMARY,user_id | PRIMARY,user_id | 4,5     | NULL |    2 | Using union(PRIMARY,user_id); Using where |
  • +----+-------------+---------+-------------+-----------------+-----------------+---------+------+------+-------------------------------------------+
  • 1 row in set (0.09 sec)
6.unique_subquery
该联接类型用于替换value IN (SELECT primary_key FROM single_table WHERE some_expr)这样的子查询的ref。注意ref列,其中第二行显示的是func,表明unique_subquery是一个函数,而不是一个普通的ref。
  • mysql> explain select * from t_order where order_id in (select order_id from t_order where user_id=10);
  • +----+--------------------+---------+-----------------+-----------------+---------+---------+------+--------+-------------+
  • | id | select_type        | table   | type            | possible_keys   | key     | key_len | ref  | rows   | Extra       |
  • +----+--------------------+---------+-----------------+-----------------+---------+---------+------+--------+-------------+
  • |  1 | PRIMARY            | t_order | ALL             | NULL            | NULL    | NULL    | NULL | 100649 | Using where |
  • |  2 | DEPENDENT SUBQUERY | t_order | unique_subquery | PRIMARY,user_id | PRIMARY | 4       | func |      1 | Using where |
  • +----+--------------------+---------+-----------------+-----------------+---------+---------+------+--------+-------------+
  • 2 rows in set (0.00 sec)
7.index_subquery
该联接类型与上面的太像了,唯一的差别就是子查询查的不是主键而是非唯一索引。
  • mysql> explain select * from t_order where user_id in (select user_id from t_order where order_id>10);
  • +----+--------------------+---------+----------------+-----------------+---------+---------+------+--------+--------------------------+
  • | id | select_type        | table   | type           | possible_keys   | key     | key_len | ref  | rows   | Extra                    |
  • +----+--------------------+---------+----------------+-----------------+---------+---------+------+--------+--------------------------+
  • |  1 | PRIMARY            | t_order | ALL            | NULL            | NULL    | NULL    | NULL | 100649 | Using where              |
  • |  2 | DEPENDENT SUBQUERY | t_order | index_subquery | PRIMARY,user_id | user_id | 5       | func |  50324 | Using index; Using where |
  • +----+--------------------+---------+----------------+-----------------+---------+---------+------+--------+--------------------------+
  • 2 rows in set (0.00 sec)
8.range
按指定的范围进行检索,很常见。
  • mysql> explain select * from t_order where user_id in (100,200,300);
  • +----+-------------+---------+-------+---------------+---------+---------+------+------+-------------+
  • | id | select_type | table   | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
  • +----+-------------+---------+-------+---------------+---------+---------+------+------+-------------+
  • |  1 | SIMPLE      | t_order | range | user_id       | user_id | 5       | NULL |    3 | Using where |
  • +----+-------------+---------+-------+---------------+---------+---------+------+------+-------------+
  • 1 row in set (0.00 sec)
9.index
在进行统计时非常常见,此联接类型实际上会扫描索引树,仅比ALL快些。
  • mysql> explain select count(*) from t_order;
  • +----+-------------+---------+-------+---------------+---------+---------+------+--------+-------------+
  • | id | select_type | table   | type  | possible_keys | key     | key_len | ref  | rows   | Extra       |
  • +----+-------------+---------+-------+---------------+---------+---------+------+--------+-------------+
  • |  1 | SIMPLE      | t_order | index | NULL          | user_id | 5       | NULL | 100649 | Using index |
  • +----+-------------+---------+-------+---------------+---------+---------+------+--------+-------------+
  • 1 row in set (0.00 sec)
10.ALL
完整的扫描全表,最慢的联接类型,尽可能的避免。
  • mysql> explain select * from t_order;
  • +----+-------------+---------+------+---------------+------+---------+------+--------+-------+
  • | id | select_type | table   | type | possible_keys | key  | key_len | ref  | rows   | Extra |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+-------+
  • |  1 | SIMPLE      | t_order | ALL  | NULL          | NULL | NULL    | NULL | 100649 |       |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+-------+
  • 1 row in set (0.00 sec)
三.extra的说明
1.Distinct
MySQL发现第1个匹配行后,停止为当前的行组合搜索更多的行。对于此项没有找到合适的例子,求指点。
2.Not exists
因为b表中的order_id是主键,不可能为NULL,所以mysql在用a表的order_id扫描t_order表,并查找b表的行时,如果在b表发现一个匹配的行就不再继续扫描b了,因为b表中的order_id字段不可能为NULL。这样避免了对b表的多次扫描。
  • mysql> explain select count(1) from t_order a left join t_order_ext b on a.order_id=b.order_id where b.order_id is null;
  • +----+-------------+-------+-------+---------------+--------------+---------+-----------------+--------+--------------------------------------+
  • | id | select_type | table | type  | possible_keys | key          | key_len | ref             | rows   | Extra                                |
  • +----+-------------+-------+-------+---------------+--------------+---------+-----------------+--------+--------------------------------------+
  • |  1 | SIMPLE      | a     | index | NULL          | express_type | 1       | NULL            | 100395 | Using index                          |
  • |  1 | SIMPLE      | b     | ref   | order_id      | order_id     | 4       | test.a.order_id |      1 | Using where; Using index; Not exists |
  • +----+-------------+-------+-------+---------------+--------------+---------+-----------------+--------+--------------------------------------+
  • 2 rows in set (0.01 sec)
3.Range checked for each record
这种情况是mysql没有发现好的索引可用,速度比没有索引要快得多。
  • mysql> explain select * from t_order t, t_order_ext s where s.order_id>=t.order_id and s.order_id<=t.order_id and t.express_type>5;
  • +----+-------------+-------+-------+----------------------+--------------+---------+------+------+------------------------------------------------+
  • | id | select_type | table | type  | possible_keys        | key          | key_len | ref  | rows | Extra                                          |
  • +----+-------------+-------+-------+----------------------+--------------+---------+------+------+------------------------------------------------+
  • |  1 | SIMPLE      | t     | range | PRIMARY,express_type | express_type | 1       | NULL |    1 | Using where                                    |
  • |  1 | SIMPLE      | s     | ALL   | order_id             | NULL         | NULL    | NULL |    1 | Range checked for each record (index map: 0x1) |
  • +----+-------------+-------+-------+----------------------+--------------+---------+------+------+------------------------------------------------+
  • 2 rows in set (0.00 sec)
4.Using filesort
在有排序子句的情况下很常见的一种情况。此时mysql会根据联接类型浏览所有符合条件的记录,并保存排序关键字和行指针,然后排序关键字并按顺序检索行。
  • mysql> explain select * from t_order order by express_type;
  • +----+-------------+---------+------+---------------+------+---------+------+--------+----------------+
  • | id | select_type | table   | type | possible_keys | key  | key_len | ref  | rows   | Extra          |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+----------------+
  • |  1 | SIMPLE      | t_order | ALL  | NULL          | NULL | NULL    | NULL | 100395 | Using filesort |
  • +----+-------------+---------+------+---------------+------+---------+------+--------+----------------+
  • 1 row in set (0.00 sec)
5.Using index
这是性能很高的一种情况。当查询所需的数据可以直接从索引树中检索到时,就会出现。上面的例子中有很多这样的例子,不再多举例了。
6.Using temporary
发生这种情况一般都是需要进行优化的。mysql需要创建一张临时表用来处理此类查询。
  • mysql> explain select * from t_order a left join t_order_ext b on a.order_id=b.order_id group by b.order_id;
  • +----+-------------+-------+------+---------------+----------+---------+-----------------+--------+---------------------------------+
  • | id | select_type | table | type | possible_keys | key      | key_len | ref             | rows   | Extra                           |
  • +----+-------------+-------+------+---------------+----------+---------+-----------------+--------+---------------------------------+
  • |  1 | SIMPLE      | a     | ALL  | NULL          | NULL     | NULL    | NULL            | 100395 | Using temporary; Using filesort |
  • |  1 | SIMPLE      | b     | ref  | order_id      | order_id | 4       | test.a.order_id |      1 |                                 |
  • +----+-------------+-------+------+---------------+----------+---------+-----------------+--------+---------------------------------+
  • 2 rows in set (0.00 sec)
7.Using where
当有where子句时,extra都会有说明。
8.Using sort_union(...)/Using union(...)/Using intersect(...)
下面的例子中user_id是一个检索范围,此时mysql会使用sort_union函数来进行索引的合并。而当user_id是一个固定值时,请参看上面type说明5.index_merge的例子,此时会使用union函数进行索引合并。
  • mysql> explain select * from t_order where order_id=100 or user_id>10;
  • +----+-------------+---------+-------------+-----------------+-----------------+---------+------+------+------------------------------------------------+
  • | id | select_type | table   | type        | possible_keys   | key             | key_len | ref  | rows | Extra                                          |
  • +----+-------------+---------+-------------+-----------------+-----------------+---------+------+------+------------------------------------------------+
  • |  1 | SIMPLE      | t_order | index_merge | PRIMARY,user_id | user_id,PRIMARY | 5,4     | NULL |    2 | Using sort_union(user_id,PRIMARY); Using where |
  • +----+-------------+---------+-------------+-----------------+-----------------+---------+------+------+------------------------------------------------+
  • 1 row in set (0.00 sec)
对于Using intersect的例子可以参看下例,user_id与express_type发生了索引交叉合并。
  • mysql> explain select * from t_order where express_type=1 and user_id=100;
  • +----+-------------+---------+-------------+----------------------+----------------------+---------+------+------+----------------------------------------------------+
  • | id | select_type | table   | type        | possible_keys        | key                  | key_len | ref  | rows | Extra                                              |
  • +----+-------------+---------+-------------+----------------------+----------------------+---------+------+------+----------------------------------------------------+
  • |  1 | SIMPLE      | t_order | index_merge | user_id,express_type | user_id,express_type | 5,1     | NULL |    1 | Using intersect(user_id,express_type); Using where |
  • +----+-------------+---------+-------------+----------------------+----------------------+---------+------+------+----------------------------------------------------+
  • 1 row in set (0.00 sec)
9.Using index for group-by
表明可以在索引中找到分组所需的所有数据,不需要查询实际的表。
  • mysql> explain select user_id from t_order group by user_id;
  • +----+-------------+---------+-------+---------------+---------+---------+------+------+--------------------------+
  • | id | select_type | table   | type  | possible_keys | key     | key_len | ref  | rows | Extra                    |
  • +----+-------------+---------+-------+---------------+---------+---------+------+------+--------------------------+
  • |  1 | SIMPLE      | t_order | range | NULL          | user_id | 5       | NULL |    3 | Using index for group-by |
  • +----+-------------+---------+-------+---------------+---------+---------+------+------+--------------------------+
  • 1 row in set (0.00 sec)
除了上面的三个说明,还需要注意rows的数值,多行之间的数值是乘积的关系,可以估算大概要处理的行数,如果乘积很大,那就很有优化的必要了。
<think>我们正在讨论MySQL中的EXPLAIN命令,用于分析查询语句的执行计划。用户要求了解如何使用EXPLAIN以及如何解读其结果。根据引用内容,我们可以总结如下:1.EXPLAIN用于模拟优化器执行SQL语句,帮助分析查询性能瓶颈(引用[2])。2.EXPLAIN输出结果包含多列,每列提供不同的信息,例如select_type、type、key等(引用[1][3][4])。3.通过分析EXPLAIN结果,可以判断查询是否使用了正确的索引,表连接顺序是否合理等(引用[3])。下面我将详细解释EXPLAIN的用法和结果解读。###如何使用EXPLAINMySQL中,使用EXPLAIN非常简单,只需在SELECT语句前加上`EXPLAIN`关键字即可。例如:```sqlEXPLAINSELECT*FROMemployeesWHEREdepartment='Sales';```也可以使用`EXPLAINFORMAT=JSON`来获取更详细的JSON格式输出(MySQL5.6.3+):```sqlEXPLAINFORMAT=JSONSELECT...;```###解读EXPLAIN结果EXPLAIN的输出结果包含以下重要列:1.**id**:查询的标识符。如果是复杂查询(如子查询或UNION),每个SELECT都会有一个唯一的id。id值越大,执行优先级越高;id相同,则从上到下执行。2.**select_type**:查询的类型。常见的有:-`SIMPLE`:简单查询(不使用UNION或子查询)。-`PRIMARY`:主查询(最外层的查询)。-`SUBQUERY`:子查询。-`DERIVED`:派生表(FROM子句中的子查询)。-`UNION`:UNION中的第二个或之后的查询。-等等(引用[1][4])。3.**table**:显示这一行数据属于哪张表。4.**partitions**:匹配的分区(如果表有分区)。5.**type**:访问类型(非常重要)。从优到差排序:-`system`:表中只有一行数据。-`const`:通过主键或唯一索引一次就找到,例如`WHEREid=1`。-`eq_ref`:唯一索引扫描,常用于主键或唯一索引关联查询。-`ref`:非唯一索引扫描。-`range`:索引范围扫描(如`BETWEEN`,`IN`,`>`等)。-`index`:全索引扫描(比全表扫描好,因为索引文件通常比数据文件小)。-`ALL`:全表扫描(最差,需优化)(引用[3])。6.**possible_keys**:可能使用的索引。7.**key**:实际使用的索引。如果为`NULL`,则没有使用索引(引用[3])。8.**key_len**:使用的索引长度(字节数)。9.**ref**:显示索引的哪一列被使用。10.**rows**:预估需要读取的行数(越小越好)。11.**filtered**:按条件过滤后剩余行数的百分比(MySQL5.7+)。12.**Extra**:额外信息。常见的有:-`Usingindex`:使用覆盖索引(无需回表)。-`Usingwhere`:使用WHERE过滤。-`Usingtemporary`:使用临时表(需优化)。-`Usingfilesort`:使用文件排序(需优化)(引用[1][3])。###示例分析假设我们有一个查询:```sqlEXPLAINSELECT*FROMordersWHEREcustomer_id=100;```可能的结果:|id|select_type|table|type|possible_keys|key|rows|Extra||----|-------------|--------|------|---------------|----------|------|-------------||1|SIMPLE|orders|ref|idx_customer|idx_customer|10|Usingwhere|解读:-`type=ref`:表示使用了非唯一索引扫描(`idx_customer`)。-`rows=10`:预估扫描10行。-`Extra=Usingwhere`:使用了WHERE过滤。###优化建议根据EXPLAIN结果优化:-如果`type`为`ALL`,考虑为WHERE条件列添加索引。-如果`Extra`出现`Usingtemporary`或`Usingfilesort`,可能需要优化查询或索引。-如果`key`为`NULL`,检查查询条件是否有合适的索引可用(引用[3])。§§相关问题§§1.EXPLAIN中的type列有哪些取值?分别代表什么含义?2.如何通过EXPLAIN结果判断查询是否需要优化?3.MySQLEXPLAIN的EXTRA列有哪些常见值?如何解读?4.如何用EXPLAIN分析连接查询(JOIN)的执行计划?</think>### MySQL EXPLAIN 用法与结果解读指南 #### 一、EXPLAIN 基础用法 在 SQL 查询语句前添加 `EXPLAIN` 关键字即可分析执行计划: ```sql EXPLAIN SELECT * FROM users WHERE age > 30; ``` 或使用 `EXPLAIN FORMAT=JSON` 获取详细 JSON 格式报告(MySQL 5.6.3+)。 #### 二、核心输出列解读 执行计划结果包含以下关键列(以表格形式呈现): | 列名 | 说明 | 优化重点 | |---------------|----------------------------------------------------------------------|-----------------------------| | **id** | 查询标识符(相同id按顺序执行,不同id从大到小执行) | 子查询执行顺序 | | **select_type** | 查询类型:<br>- `SIMPLE`:简单查询<br>- `PRIMARY`:主查询<br>- `SUBQUERY`:子查询 | 识别复杂查询结构 | | **table** | 访问的表名或别名 | 表访问顺序 | | **type** | **访问类型(性能关键指标)**:<br>`system` > `const` > `eq_ref` > `ref` > `range` > `index` > `ALL` | 避免出现`ALL`(全表扫描) | | **possible_keys** | 可能使用的索引 | 索引选择合理性 | | **key** | 实际使用的索引 | 验证索引是否生效 | | **key_len** | 使用的索引长度(字节) | 索引利用率 | | **rows** | 预估扫描行数 | 数值越小性能越好 | | **Extra** | **额外信息(优化核心)**:<br>- `Using index`:覆盖索引<br>- `Using where`:WHERE过滤<br>- `Using temporary`:临时表<br>- `Using filesort`:文件排序 | 重点关注需优化的项 | #### 三、重点列深度解析 1. **type 列详解**(性能从优到差排序): - `const`:通过主键/唯一索引查找单行(最优) - `eq_ref`:JOIN 时使用主键/唯一索引关联 - `ref`:非唯一索引扫描(常见于普通索引) - `range`:索引范围扫描(如 `BETWEEN`, `>`) - `index`:全索引扫描(比全表扫描稍好) - `ALL`:全表扫描(需优化) 2. **Extra 列关键值**: - ✅ `Using index`:查询仅用索引无需回表(理想状态) - ⚠️ `Using where`:服务器对存储引擎返回的数据进行过滤 - ❌ `Using temporary`:需创建临时表(GROUP BY/ORDER BY 无索引时常见) - ❌ `Using filesort`:额外排序操作(需优化 ORDER BY) #### 四、优化案例分析 **问题查询**: ```sql EXPLAIN SELECT * FROM orders WHERE user_id = 100 ORDER BY order_date; ``` **可能结果与优化**: | id | select_type | table | type | key | rows | Extra | |----|-------------|--------|------|------|------|----------------| | 1 | SIMPLE | orders | ref | NULL | 2000 | Using where; Using filesort | **优化建议**: 1. 为 `user_id` 添加索引避免全表扫描: ```sql ALTER TABLE orders ADD INDEX idx_user(user_id); ``` 2. 为排序字段添加复合索引消除 `filesort`: ```sql ALTER TABLE orders ADD INDEX idx_user_date(user_id, order_date); ``` 优化后结果变化: | type | key | Extra | |------|---------------|----------------| | ref | idx_user_date | Using index | #### 五、高级应用技巧 1. **连接查询分析**: ```sql EXPLAIN SELECT * FROM users u JOIN orders o ON u.id = o.user_id WHERE u.country = 'US'; ``` - 观察表连接顺序(id 相同则按 table 列顺序) - 检查是否使用索引连接(`eq_ref` 或 `ref`) 2. **JSON 格式分析**(MySQL 5.6+): ```sql EXPLAIN FORMAT=JSON SELECT ... ``` 可获取成本估算、子查询详情等深度信息。 > 提示:实际优化中需结合 `SHOW INDEX FROM table_name` 查看索引基数,避免索引失效[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值