Mysql left join o r条件性能问题解决方法

问题

select mu.* from mission_user mu left join  mission_daily md on mu.`user_id`=md.user_id and md.mission_id=mu.mission_id 
            left join mission_weekly mw on mu.`user_id`=mw.user_id and mw.mission_id=mu.mission_id 
            where (md.day='2019-02-21' and md.status='GOING' and md.`user_id`=478) or (mw.year_week=201909 and mw.status='GOING' and mw.`user_id`=478) 
             limit 0,20
//执行时间:10.2s
  • 执行时间 10.2s

排查,各去除一个or 条件

select mu.* from mission_user mu left join  mission_daily md on mu.`user_id`=md.user_id and md.mission_id=mu.mission_id 
            left join mission_weekly mw on mu.`user_id`=mw.user_id and mw.mission_id=mu.mission_id 
            where (mw.year_week=201909 and mw.status='GOING' and mw.`user_id`=478) 
             limit 0,20
//执行时间:35ms
select mu.* from mission_user mu left join  mission_daily md on mu.`user_id`=md.user_id and md.mission_id=mu.mission_id 
            left join mission_weekly mw on mu.`user_id`=mw.user_id and mw.mission_id=mu.mission_id 
            where (md.day='2019-02-21' and md.status='GOING' and md.`user_id`=478)  
             limit 0,20
//执行时间:32ms

慢原因分析

由于为对主表加条件导致,mission_user 整表查询出来在left join 导致缓慢.

解决方法,加入mission_user 条件到where

select mu.* from mission_user mu left join  mission_daily md on mu.`user_id`=md.user_id and md.mission_id=mu.mission_id 
            left join mission_weekly mw on mu.`user_id`=mw.user_id and mw.mission_id=mu.mission_id 
            where mu.user_id=478 and ((md.day='2019-02-21' and md.status='GOING' and md.`user_id`=478) or (mw.year_week=201909 and mw.status='GOING' and mw.`user_id`=478) )
             limit 0,20
//执行时间:116ms
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容