↑↑↑ 欢迎 点赞、关注、收藏!!!,10 年 IT 行业老鸟,持续分享更多 IT 干货
目录
慢 SQL 问题排查
参考:https://www.yuque.com/hollis666/go2k1v/dxmpt2
背景
线上有一个定时任务,连续执行多次失败。
日志排查发现,有大量报错
在日志上下文不远处,定位到这条慢 SQL
select distinct buyer_id as buyerId, seller_id as sellerId from fraud_risk_case WHERE subject_id_enum = 'BUYER_SELLER_BOTH' and (buyer_id = ? orseller_id = ? ) and product_type_enum = ? order by id desc limit 100
这条SQL的主要目的是:找到是否有买卖家之间存在关联关系的数据。
分析
执行 explain,看一下
可以发现,type = index ,extra = Using where; Using index 。表示这个 SQL 因为不符合最左前缀匹配,而扫描了整颗索引树,故而很慢。
查看这张表的建表语句,确实存在 subject_id_enum 和 product_type_enum 字段的联合索引,但是,这个字段并不是前导列:
idx_subject_product(subject_id, subject_id_enum, product_type)
解决问题
只需要增加正确的索引,或者修改SQL就行了。
ALTER TABLE `fraud_risk_case` ADD KEY `idx_subject_type_product_user` (`subject_id_enum`,`product_type_enum`,`buyer_id`,`seller_id`);
再 执行 explain,看一下
看到 type=ref,说明用到了普通索引,并且rows也变少了,大大提升了整个SQL查询速度。
定时任务也执行成功了。
参考链接
Java 八股/07-MySQL/分析 SQL 执行计划.md
↑↑↑ 欢迎 点赞、关注、收藏!!!,10 年 IT 行业老鸟,持续分享更多 IT 干货