[英]Is there a better way to structure this MySQL query to make it run faster?
我使用查詢 output 一個排行榜。 其中output按代理商賺取的佣金金額排序。 我注意到運行查詢需要很長時間(+- 30 秒)。 我想知道是否通過以不同的方式構造(或其他解決方案)查詢,我可以使運行時更快。
這是查詢:
SELECT * FROM
(SELECT agent,
COUNT(*) as sales,
(4*(SELECT COUNT(*)
FROM Sales Sales2
WHERE Sales2.agent=Sales.agent AND finalized_at BETWEEN '2020-11-01 00:00:00' AND '2020-11-27 23:59:59' AND flow=117))
/
(SELECT SUM(uren)
FROM Uren
WHERE datum BETWEEN '2020-11-01 00:00:00' AND '2020-11-27 23:59:59' AND agent=Sales.agent) as sph,
(SELECT COUNT(*)
FROM Sales Sales3
WHERE Sales3.agent=Sales.agent AND finalized_at BETWEEN '2020-11-27 00:00:00' AND '2020-11-27 23:59:59' AND flow=165) as telecom
FROM Sales
WHERE finalized_at BETWEEN '2020-11-27 00:00:00' AND '2020-11-27 23:59:59' AND flow=117
GROUP BY agent ) r
ORDER BY sales * sph * (case when sph > 1.5 then 10 else 7.5 end ) * 0.5184 + telecom * 3.75 desc;
這是 EXPLAIN 的結果
1 PRIMARY <derived2> NULL ALL NULL NULL NULL NULL 165 100.00 Using filesort
2 DERIVED Sales NULL ALL NULL NULL NULL NULL 14899 1.11 Using where; Using temporary; Using filesort
5 DEPENDENT SUBQUERY Sales3 NULL ALL NULL NULL NULL NULL 14899 0.11 Using where
4 DEPENDENT SUBQUERY Uren NULL ALL NULL NULL NULL NULL 7286 1.11 Using where
3 DEPENDENT SUBQUERY Sales2 NULL ALL NULL NULL NULL NULL 14899 0.11 Using where
您可以嘗試截斷這些日期,以便數據庫只考慮全天,從而處理更少的信息。
像這樣:
SELECT * FROM
(SELECT agent,
COUNT(*) as sales,
(4*(SELECT COUNT(*)
FROM Sales Sales2
WHERE Sales2.agent=Sales.agent AND trunc(finalized_at) BETWEEN '2020-11-01' AND '2020-11-27' AND flow=117))
/
(SELECT SUM(uren)
FROM Uren
WHERE trunc(datum) BETWEEN '2020-11-01' AND '2020-11-27' AND agent=Sales.agent) as sph,
(SELECT COUNT(*)
FROM Sales Sales3
WHERE Sales3.agent=Sales.agent AND trunc(finalized_at) = '2020-11-27' AND flow=165) as telecom
FROM Sales
WHERE trunc(finalized_at) = '2020-11-27' AND flow=117
GROUP BY agent ) r
ORDER BY sales * sph * (case when sph > 1.5 then 10 else 7.5 end ) * 0.5184 + telecom * 3.75 desc;
這部分:
finalized_at BETWEEN '2020-11-27 00:00:00' AND '2020-11-27 23:59:59'
改為:
trunc(finalized_at) = '2020-11-27'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.