前言

在mysql中 describe 和 explain 语句是相同的意思。describe 语句多用于获取表结构,而 explain 语句用于获取查询执行计划(用于解释mysql如何执行查询语句)。

通过 explain 语句可以帮助我们发现表格的哪些字段上需要建立索引,用于加速查询。也可以使用 explain 检查优化器是否使用最优的顺序来连接表。

explain 语法如下:

{explain | describe | desc}
    tbl_name [col_name | wild]

{explain | describe | desc}
    [explain_type]
    {explainable_stmt | for connection connection_id}

{explain | describe | desc} analyze [format = tree] select_statement

explain_type: {
    format = format_name
}

format_name: {
    traditional
  | json
  | tree
}

explainable_stmt: {
    select statement
  | table statement
  | delete statement
  | insert statement
  | replace statement
  | update statement
}

1、获取表结构

describe 是 show columns 的快捷方式,也可以用于显示view 的信息,show columns提供了更多的列信息。

show create table, show table status, show index 也用于提供表信息。

describe 默认显示所有列的信息,如果指定了 col_name 将只显示该列的信息。wild 用于指定模式串,可以使用sql通配符 % 和 _。如果指定了 wild ,将显示与模式串匹配的列信息。如果没有特殊字符(空格或其它特殊字符),模式串不需要使用引号括起来。

describe city;
# 等同于
show columns from city;

2、获取执行计划信息

  • describe 可以查询 select, delete, insert, replace, update 的执行信息。mysql 8.0.19 也可以查询 table 语句。
  • mysql从优化器获取可解释语句的执行计划信息,包括参与的表、顺序等信息。
  • 如果使用for connection connection_id语句,mysql显示该命名连接的执行计划。
  • explain 语句产生的执行计划信息可以通过 show warnings 显示。
  • format 选项用于指定输出格式,traditional 是默认的输出格式,以表格形式显示。

explain 需要的权限与被执行解释语句的权限相同,解释 view 语句时需要 show view 权限,explain … for connection需要 process 权限。
可以使用 select straight_join 来告诉优化器使用 select 指定的连接顺序。

3、使用 explain analyze 获取信息

mysql 8.0.18 推荐使用 explain analyze,该语句可以输出语句的执行时间和以下信息

  • 预计执行时间
  • 预计返回的行数
  • 返回第一行的时间
  • 迭代器的执行时间,单位毫秒
  • 迭代器返回的行数
  • 执行循环的次数

查询信息以 tree 的形式输出,每个节点代表一个迭代器。explain analyze 可以用于 select 语句,以及多表的 update 和 delete 语句,mysql 8.0.19 以后也可以用于 table 语句。explain analyze 不能使用 for connection 。

mysql 8.0.20 以后可以通过 kill query 或 ctrl-c 终止该语句的执行。

mysql> explain analyze select * from t1 join t2 on (t1.c1 = t2.c2)\g
*************************** 1. row ***************************
explain: -> inner hash join (t2.c2 = t1.c1)  (cost=4.70 rows=6)
(actual time=0.032..0.035 rows=6 loops=1)
   -> table scan on t2  (cost=0.06 rows=6)
(actual time=0.003..0.005 rows=6 loops=1)
   -> hash
       -> table scan on t1  (cost=0.85 rows=6)
(actual time=0.018..0.022 rows=6 loops=1)

mysql> explain analyze select * from t3 where i > 8\g
*************************** 1. row ***************************
explain: -> filter: (t3.i > 8)  (cost=1.75 rows=5)
(actual time=0.019..0.021 rows=6 loops=1)
   -> table scan on t3  (cost=1.75 rows=15)
(actual time=0.017..0.019 rows=15 loops=1)

mysql> explain analyze select * from t3 where pk > 17\g
*************************** 1. row ***************************
explain: -> filter: (t3.pk > 17)  (cost=1.26 rows=5)
(actual time=0.013..0.016 rows=5 loops=1)
   -> index range scan on t3 using primary  (cost=1.26 rows=5)
(actual time=0.012..0.014 rows=5 loops=1)

总结 

到此这篇关于mysql中explain语句及用法的文章就介绍到这了,更多相关mysql explain语句内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!