# 一、慢查询优化基本步骤
【1】先运行看看是否真的很慢,注意设置SQL_NO_CACHE
(查询时不使用缓存);
【2】where
条件单表查,锁定最小返回记录表。这句话的意思是把查询语句的where
都应用到表中返回的记录数最小的表开始查起,单表每个字段分别查询,看哪个字段的区分度最高;
【3】explain
查看执行计划,是否与2
预期一致(从锁定记录较少的表开始查询);
【4】order by limit
形式的sql
语句让排序的表优先查;
【5】了解业务方使用场景;
【6】加索引时参照建索引的几大原则;
【7】观察结果,不符合预期继续从1分析;
# 二、几个慢查询案例
下面几个例子详细解释了如何分析和优化慢查询
# 1、复杂语句写法
很多情况下,我们写SQL
只是为了实现功能,这只是第一步,不同的语句书写方式对于效率往往有本质的差别,这要求我们对mysql
的执行计划和索引原则有非常清楚的认识,请看下面的语句:
select
distinct cert.emp_id
from
cm_log cl
inner join
(
select
emp.id as emp_id,
emp_cert.id as cert_id
from
employee emp
left join
emp_certificate emp_cert
on emp.id = emp_cert.emp_id
where
emp.is_deleted=0
) cert
on (
cl.ref_table='Employee'
and cl.ref_oid= cert.emp_id
)
or (
cl.ref_table='EmpCertificate'
and cl.ref_oid= cert.cert_id
)
where
cl.last_upd_date >='2013-11-07 15:03:00'
and cl.last_upd_date<='2013-11-08 16:00:00';
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
【1】先运行一下,53
条记录1.87
秒,又没有用聚合语句,比较慢
53 rows in set (1.87 sec)
【2】explain
+----+-------------+------------+-------+---------------------------------+-----------------------+---------+-------------------+-------+--------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+-------+---------------------------------+-----------------------+---------+-------------------+-------+--------------------------------+
| 1 | PRIMARY | cl | range | cm_log_cls_id,idx_last_upd_date | idx_last_upd_date | 8 | NULL | 379 | Using where; Using temporary |
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 63727 | Using where; Using join buffer |
| 2 | DERIVED | emp | ALL | NULL | NULL | NULL | NULL | 13317 | Using where |
| 2 | DERIVED | emp_cert | ref | emp_certificate_empid | emp_certificate_empid | 4 | meituanorg.emp.id | 1 | Using index |
+----+-------------+------------+-------+---------------------------------+-----------------------+---------+-------------------+-------+--------------------------------+
2
3
4
5
6
7
8
简述一下执行计划,首先mysql
根据idx_last_upd_date
索引扫描cm_log
表获得379
条记录;然后查表扫描了63727
条记录,分为两部分,derived
[衍生的]表示构造表,也就是不存在的表,可以简单理解成是一个语句形成的结果集,后面的数字表示语句的ID
。derived2
表示的是ID = 2
的查询构造了虚拟表,并且返回了63727
条记录。我们再来看看ID = 2
的语句究竟做了写什么返回了这么大量的数据,首先全表扫描employee
表13317
条记录,然后根据索引emp_certificate_empid
关联emp_certificate
表,rows = 1
表示,每个关联都只锁定了一条记录,效率比较高。获得后,再和cm_log
的379
条记录根据规则关联。从执行过程上可以看出返回了太多的数据,返回的数据绝大部分cm_log
都用不到,因为cm_log
只锁定了379
条记录。
如何优化呢?可以看到我们在运行完后还是要和cm_log
做join
,那么我们能不能运行之前和cm_log
做join
呢?仔细分析语句不难发现,其基本思想是如果cm_log
的ref_table
是EmpCertificate
就关联emp_certificate
表,如果ref_table
是Employee
就关联employee
表,我们完全可以拆成两部分,并用union
连接起来,注意这里用union
,而不用union all
是因为原语句有“distinct”来得到唯一的记录,而union
恰好具备了这种功能。如果原语句中没有distinct
不需要去重,我们就可以直接使用union all
了,因为使用union
需要去重的动作,会影响SQL性能。
优化过的语句如下:
select
emp.id
from
cm_log cl
inner join
employee emp
on cl.ref_table = 'Employee'
and cl.ref_oid = emp.id
where
cl.last_upd_date >='2013-11-07 15:03:00'
and cl.last_upd_date<='2013-11-08 16:00:00'
and emp.is_deleted = 0
union
select
emp.id
from
cm_log cl
inner join
emp_certificate ec
on cl.ref_table = 'EmpCertificate'
and cl.ref_oid = ec.id
inner join
employee emp
on emp.id = ec.emp_id
where
cl.last_upd_date >='2013-11-07 15:03:00'
and cl.last_upd_date<='2013-11-08 16:00:00'
and emp.is_deleted = 0
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
【3】不需要了解业务场景,只需要改造的语句和改造之前的语句保持结果一致;
【4】现有索引可以满足,不需要建索引;
【5】用改造后的语句实验一下,只需要10ms
降低了近200
倍!
+----+--------------+------------+--------+---------------------------------+-------------------+---------+-----------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------+------------+--------+---------------------------------+-------------------+---------+-----------------------+------+-------------+
| 1 | PRIMARY | cl | range | cm_log_cls_id,idx_last_upd_date | idx_last_upd_date | 8 | NULL | 379 | Using where |
| 1 | PRIMARY | emp | eq_ref | PRIMARY | PRIMARY | 4 | meituanorg.cl.ref_oid | 1 | Using where |
| 2 | UNION | cl | range | cm_log_cls_id,idx_last_upd_date | idx_last_upd_date | 8 | NULL | 379 | Using where |
| 2 | UNION | ec | eq_ref | PRIMARY,emp_certificate_empid | PRIMARY | 4 | meituanorg.cl.ref_oid | 1 | |
| 2 | UNION | emp | eq_ref | PRIMARY | PRIMARY | 4 | meituanorg.ec.emp_id | 1 | Using where |
| NULL | UNION RESULT | <union1,2> | ALL | NULL | NULL | NULL | NULL | NULL | |
+----+--------------+------------+--------+---------------------------------+-------------------+---------+-----------------------+------+-------------+
53 rows in set (0.01 sec)
2
3
4
5
6
7
8
9
10
11
# 2、明确应用场景
举这个例子的目的在于颠覆我们对列的区分度的认知,一般上我们认为区分度越高的列,越容易锁定更少的记录,但在一些特殊的情况下,这种理论是有局限性的。
select
*
from
stage_poi sp
where
sp.accurate_result=1
and (
sp.sync_status=0
or sp.sync_status=2
or sp.sync_status=4
);
2
3
4
5
6
7
8
9
10
11
【1】先看看运行多长时间,951
条数据6.22
秒,真的很慢。
951 rows in set (6.22 sec)
【2】先explain
,rows
达到了361
万,type = ALL
表明是全表扫描。
+----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
| 1 | SIMPLE | sp | ALL | NULL | NULL | NULL | NULL | 3613155 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
2
3
4
5
【3】所有字段都应用查询返回记录数,因为是单表查询1
已经做过了951
条。
【4】让explain
的rows
尽量逼近951
。
【5】看一下accurate_result = 1
的记录数:
select count(*),accurate_result from stage_poi group by accurate_result;
+----------+-----------------+
| count(*) | accurate_result |
+----------+-----------------+
| 1023 | -1 |
| 2114655 | 0 |
| 972815 | 1 |
+----------+-----------------+
2
3
4
5
6
7
8
【6】我们看到accurate_result
这个字段的区分度非常低,整个表只有-1
,0
,1
三个值,加上索引也无法锁定特别少量的数据。
【7】再看一下sync_status
字段的情况:
select count(*),sync_status from stage_poi group by sync_status;
+----------+-------------+
| count(*) | sync_status |
+----------+-------------+
| 3080 | 0 |
| 3085413 | 3 |
+----------+-------------+
2
3
4
5
6
7
【8】同样的区分度也很低,根据理论,也不适合建立索引。
【9】问题分析到这,好像得出了这个表无法优化的结论,两个列的区分度都很低,即便加上索引也只能适应这种情况,很难做普遍性的优化,比如当sync_status 0
、3
分布的很平均,那么锁定记录也是百万级别的。
【10】找业务方去沟通,看看使用场景。业务方是这么来使用这个SQL
语句的,每隔五分钟会扫描符合条件的数据,处理完成后把sync_status
这个字段变成1,五分钟符合条件的记录数并不会太多,1000
个左右。了解了业务方的使用场景后,优化这个SQL
就变得简单了,因为业务方保证了数据的不平衡,如果加上索引可以过滤掉绝大部分不需要的数据。
【11】根据建立索引规则,使用如下语句建立索引
alter table stage_poi add index idx_acc_status(accurate_result,sync_status);
【12】观察预期结果,发现只需要200ms
,快了30
多倍。
952 rows in set (0.20 sec)
我们再来回顾一下分析问题的过程,单表查询相对来说比较好优化,大部分时候只需要把where
条件里面的字段依照规则加上索引就好,如果只是这种“无脑”优化的话,显然一些区分度非常低的列,不应该加索引的列也会被加上索引,这样会对插入、更新性能造成严重的影响,同时也有可能影响其它的查询语句。所以我们调查SQL
的使用场景非常关键,我们只有知道这个业务场景,才能更好地辅助我们更好的分析和优化查询语句。
# 3、无法优化的语句
select
c.id,
c.name,
c.position,
c.sex,
c.phone,
c.office_phone,
c.feature_info,
c.birthday,
c.creator_id,
c.is_keyperson,
c.giveup_reason,
c.status,
c.data_source,
from_unixtime(c.created_time) as created_time,
from_unixtime(c.last_modified) as last_modified,
c.last_modified_user_id
from
contact c
inner join
contact_branch cb
on c.id = cb.contact_id
inner join
branch_user bu
on cb.branch_id = bu.branch_id
and bu.status in (
1,
2)
inner join
org_emp_info oei
on oei.data_id = bu.user_id
and oei.node_left >= 2875
and oei.node_right <= 10802
and oei.org_category = - 1
order by
c.created_time desc limit 0 ,
10;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
先看语句运行多长时间,10
条记录用了13
秒,已经不可忍受。
10 rows in set (13.06 sec)
执行 explain
+----+-------------+-------+--------+-------------------------------------+-------------------------+---------+--------------------------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+-------------------------------------+-------------------------+---------+--------------------------+------+----------------------------------------------+
| 1 | SIMPLE | oei | ref | idx_category_left_right,idx_data_id | idx_category_left_right | 5 | const | 8849 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | bu | ref | PRIMARY,idx_userid_status | idx_userid_status | 4 | meituancrm.oei.data_id | 76 | Using where; Using index |
| 1 | SIMPLE | cb | ref | idx_branch_id,idx_contact_branch_id | idx_branch_id | 4 | meituancrm.bu.branch_id | 1 | |
| 1 | SIMPLE | c | eq_ref | PRIMARY | PRIMARY | 108 | meituancrm.cb.contact_id | 1 | |
+----+-------------+-------+--------+-------------------------------------+-------------------------+---------+--------------------------+------+----------------------------------------------+
2
3
4
5
6
7
8
从执行计划上看,mysql
先查org_emp_info
表扫描8849
记录,再用索引idx_userid_status
关联branch_user
表,再用索引idx_branch_id
关联contact_branch
表,最后主键关联contact
表。rows
返回的都非常少,看不到有什么异常情况。我们在看一下语句,发现后面有order by + limit
组合,会不会是排序量太大搞的?于是我们简化SQL
,去掉后面的order by
和limit
,看看到底用了多少记录来排序。
select
count(*)
from
contact c
inner join
contact_branch cb
on c.id = cb.contact_id
inner join
branch_user bu
on cb.branch_id = bu.branch_id
and bu.status in (
1,
2)
inner join
org_emp_info oei
on oei.data_id = bu.user_id
and oei.node_left >= 2875
and oei.node_right <= 10802
and oei.org_category = - 1
+----------+
| count(*) |
+----------+
| 778878 |
+----------+
1 row in set (5.19 sec)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
发现排序之前居然锁定了778878
条记录,如果针对70
万的结果集排序,将是灾难性的,怪不得这么慢,那我们能不能换个思路,先根据contact
的created_time
排序,再来join
会不会比较快呢?于是改造成下面的语句,也可以用straight_join
来优化:
select
c.id,
c.name,
c.position,
c.sex,
c.phone,
c.office_phone,
c.feature_info,
c.birthday,
c.creator_id,
c.is_keyperson,
c.giveup_reason,
c.status,
c.data_source,
from_unixtime(c.created_time) as created_time,
from_unixtime(c.last_modified) as last_modified,
c.last_modified_user_id
from
contact c
where
exists (
select
1
from
contact_branch cb
inner join
branch_user bu
on cb.branch_id = bu.branch_id
and bu.status in (
1,
2)
inner join
org_emp_info oei
on oei.data_id = bu.user_id
and oei.node_left >= 2875
and oei.node_right <= 10802
and oei.org_category = - 1
where
c.id = cb.contact_id
)
order by
c.created_time desc limit 0 ,
10;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
验证一下效果 预计在1ms
内,提升了13000
多倍!
10 rows in set (0.00 sec)
本以为至此大工告成,但我们在前面的分析中漏了一个细节,先排序再join
和先join
再排序理论上开销是一样的,为何提升这么多是因为有一个limit!
大致执行过程是:mysql
先按索引排序得到前10
条记录,然后再去join
过滤,当发现不够10
条的时候,再次去10
条,再次join
,这显然在内层join
过滤的数据非常多的时候,将是灾难的,极端情况,内层一条数据都找不到,mysql
还傻乎乎的每次取10
条,几乎遍历了这个数据表!用不同参数的SQL
试验下:
select
sql_no_cache c.id,
c.name,
c.position,
c.sex,
c.phone,
c.office_phone,
c.feature_info,
c.birthday,
c.creator_id,
c.is_keyperson,
c.giveup_reason,
c.status,
c.data_source,
from_unixtime(c.created_time) as created_time,
from_unixtime(c.last_modified) as last_modified,
c.last_modified_user_id
from
contact c
where
exists (
select
1
from
contact_branch cb
inner join
branch_user bu
on cb.branch_id = bu.branch_id
and bu.status in (
1,
2)
inner join
org_emp_info oei
on oei.data_id = bu.user_id
and oei.node_left >= 2875
and oei.node_right <= 2875
and oei.org_category = - 1
where
c.id = cb.contact_id
)
order by
c.created_time desc limit 0 ,
10;
Empty set (2 min 18.99 sec)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2 min 18.99 sec!
比之前的情况还糟糕很多。由于mysql
的nested loop
机制,遇到这种情况,基本是无法优化的。这条语句最终也只能交给应用系统去优化自己的逻辑了。
TIP
通过这个例子我们可以看到,并不是所有语句都能优化,而往往我们优化时,由于SQL
用例回归时落掉一些极端情况,会造成比原来还严重的后果。所以,第一:不要指望所有语句都能通过SQL
优化,第二:不要过于自信,只针对具体case
来优化,而忽略了更复杂的情况。
慢查询的案例就分析到这儿,以上只是一些比较典型的案例。我们在优化过程中遇到过超过1000行,涉及到16
个表join
的“垃圾SQL”,也遇到过线上线下数据库差异导致应用直接被慢查询拖死,也遇到过varchar
等值比较没有写单引号,还遇到过笛卡尔积查询直接把从库搞死。再多的案例其实也只是一些经验的积累,如果我们熟悉查询优化器、索引的内部原理,那么分析这些案例就变得特别简单了。
TIP
任何数据库层面的优化都抵不上应用系统的优化,同样是MySQL
,可以用来支撑Google
/FaceBook
/Taobao
应用,但可能连你的个人网站都撑不住。套用最近比较流行的话:“查询容易,优化不易,且写且珍惜!”