关于数据库:SQL优化in

40次阅读

共计 777 个字符,预计需要花费 2 分钟才能阅读完成。

原始 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 拆分后,遍历的表多了,应用组全但更高效

正文完
 0