SQL调优 - 修改执行计划加速SQL查询
在某些复杂sql语句,或者数据分布不均衡的table中(未启动直方图统计),默认的执行计划可能不是最佳方案,此时我们可以通过控制优化器策略引导执行计划发生改变。
先看一个案例
某生产库中的sql执行效率非常低,查看执行计划发现驱动表扫描行数很多且不走索引。
explain
SELECT count(distinct u.id)
FROM sys_t_audience_member m
JOIN org_user u on u.id = m.user_id
JOIN sys_t_audience_object o ON m.condition_id = o.condition_id
AND o.activity_type = 'E'
AND m.is_deleted = 0
AND o.business_id = 1580755887218814978
where u.shared_1 & 4096 = 4096 and u.`status` = 1 and u.IS_DELETED = 1;
+----+-------------+-------+------------+------+------------------------------------+------------------+---------+-------------------------+---------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+------------+------+------------------------------------+------------------+---------+-------------------------+---------+----------+-------------+
| 1 | SIMPLE | u | NULL | ALL | PRIMARY | NULL | NULL | NULL | 1041455 | 1.00 | Using where |
| 1 | SIMPLE | m | NULL | ref | idx_condition_id,idx_tenant_user | idx_tenant_user | 9 | rxt_exam.u.ID | 5 | 10.00 | Using where |
| 1 | SIMPLE | o | NULL | ref | idx_condition_id,idx_activity_type | idx_condition_id | 9 | rxt_exam.m.CONDITION_ID | 5 | 3.38 | Using where |
+----+-------------+-------+------------+------+------------------------------------+------------------+---------+-------------------------+---------+----------+-------------+
3 rows in set, 1 warning (0.00 sec)