explain.md 1.6 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4
# EXPLAIN

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

fix bug  
张志晨 已提交
5
```sql
6 7 8 9 10 11 12 13
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)
M
Mars Liu 已提交
14 15 16 17 18 19 20
select orders.id, content
from orders
         join r on orders.id = r.id;
```

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

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

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

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

M
Mars Liu 已提交
28 29 30 31
## 答案

在测试库使用 

fix bug  
张志晨 已提交
32
```sql
33 34 35 36 37 38 39 40
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)
M
Mars Liu 已提交
41 42 43 44 45 46 47
select orders.id, content
from orders
         join r on orders.id = r.id;
```

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

fix bug  
张志晨 已提交
48
```sql
49 50 51 52 53 54 55 56
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)
M
Mars Liu 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
select orders.id 
from orders
         join r on orders.id = r.id;
```

进行详细分析。

## 选项

### A

对查询设计的字段加索引

### B

备份数据库,删除重建

### C

使用

fix bug  
张志晨 已提交
78
```sql
79 80 81 82 83 84 85 86
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)
M
Mars Liu 已提交
87 88 89 90 91 92
select orders.id 
from orders
         join r on orders.id = r.id;
```

进行剖分。