explain.md 2.1 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# EXPLAIN

Joe 从交易服务中发现了一些高频查询和慢查询,例如

```mysql
with recursive r(id) as (select id
                         from orders
                         where id = $1
                         union
                         select d.id
                         from orders as d
                                  join r on d.id = r.id + 1)
select orders.id, content
from orders
         join r on orders.id = r.id;
```

,他应该从何入手分析优化?

M
Mars Liu 已提交
20 21
<hr/>

M
Mars Liu 已提交
22
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill)
F
feilong 已提交
23

M
Mars Liu 已提交
24 25
* `show databases` 列出所有数据库
* `show tables` 列出所有表
M
Mars Liu 已提交
26

M
Mars Liu 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
## 答案

在测试库使用 

```mysql
explain with recursive r(id) as (select id
                         from orders
                         where id = $1
                         union
                         select d.id
                         from orders as d
                                  join r on d.id = r.id + 1)
select orders.id, content
from orders
         join r on orders.id = r.id;
```

进行剖分,对于需要了解详细执行计划的使用

```mysql
explain analyze with recursive r(id) as (select id
                         from orders
                         where id = 100
                         union
                         select d.id
                         from orders as d
                                  join r on d.id = r.id + 1)
select orders.id 
from orders
         join r on orders.id = r.id;
```

进行详细分析。

## 选项

### A

对查询设计的字段加索引

### B

备份数据库,删除重建

### C

使用

```mysql
analyze with recursive r(id) as (select id
                         from orders
                         where id = 100
                         union
                         select d.id
                         from orders as d
                                  join r on d.id = r.id + 1)
select orders.id 
from orders
         join r on orders.id = r.id;
```

进行剖分。