继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

SQL优化—in

阿丽是我
关注TA
已关注
手记 9
粉丝 0
获赞 7

原始SQL(执行时间80s+)

SELECT count(id) as id FROM task WHERE cid=100015	AND  sid IN(112310,112316,106959,110780,112324,112331,112317)  	AND  flag='9'

优化后SQL(平均执行时间100ms)

select sum(id) as id  from (
SELECT count(*) as id FROM task WHERE AND  cid=123456  AND  sid=112310  AND  flag=9
union all
SELECT count(*) as id FROM task WHERE AND  cid=123456  AND  sid=112316  AND  flag=9
union all
SELECT count(*) as id FROM task WHERE AND  cid=123456  AND  sid=106959  AND  flag=9
union all
SELECT count(*) as id FROM task WHERE AND  cid=123456  AND  sid=110780  AND  flag=9
union all
SELECT count(*) as id FROM task WHERE AND  cid=123456  AND  sid=112324  AND  flag=9
union all
SELECT count(*) as id FROM task WHERE AND  cid=123456  AND  sid=112331  AND  flag=9
union all
SELECT count(*) as id FROM task WHERE AND  cid=123456  AND  sid=112317  AND  flag=9
) t

说明:
mysql版本5.6
表总的数据量60万+
cid和flag为int类型,参数去掉引号,避免隐式转换
(cid sid flag)是组合索引,使用uinon all拆分后,遍历的表多了,使用组全但更高效
file

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP