SQL子查询优化多个聚合操作

时间:2018-04-20 14:50:18

标签: mysql sql

我试图通过项目找到不同表和组的平均值和总和。我还想将返回的表压缩成一行。 所以对于我的子查询,我得到了这个结果

enter image description here

使用外部查询我期望这样: enter image description here

到目前为止这是我的sql代码。它有效,但它的性能非常慢,我不确定为什么或如何优化它。

select sum(sub.count) as count, avg(sub.opened) as opened,
avg(sub.clicked) as clicked, avg(sub.started_watching) as started_watching,
sum(sub.views) as views
from (
select p.id, count(e.id) as count, 
avg(e.opened) as opened, avg(e.read_email) as clicked,
avg(e.started_video) as started_watching, sum(e.views) as views
from projects p
inner join guests g
on g.project_id = p.id
inner join videos v
on v.guest_id = g.id
inner join emails e
on e.video_id=v.id
group by p.id) sub; 

1 个答案:

答案 0 :(得分:0)

查看您的查询主要问题与子查询结果的创建有关 所以重要的是改进这个查询,例如在每个表的连接所涉及的列上添加适当的索引 adn最终为select中使用的列添加复合索引(在连接中使用的列之后)

       CASE
         WHEN b.data IS NULL
         THEN c.info
         ELSE b.info
       END  AS b_or_c_info

所以请确保你有适当的索引

  Select  sum(sub.count) as count
        , avg(sub.opened) as opened
        , avg(sub.clicked) as clicked
        , avg(sub.started_watching) as started_watching
        , sum(sub.views) as views
  from (
    select p.id
        , count(e.id) as count
        , avg(e.opened) as opened
        , avg(e.read_email) as clicked
        , avg(e.started_video) as started_watching
        , sum(e.views) as views
    from projects p
    inner join guests g on g.project_id = p.id
    inner join videos v on v.guest_id = g.id
    inner join emails e on e.video_id=v.id
    group by p.id
  ) sub;