繁体   English   中英

有没有更好的方法来构建这个 MySQL 查询以使其运行得更快?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM