【问题标题】:Mysql Distinct Sum Aggregation On Join OperationMysql Distinct Sum Aggregation On Join 操作
【发布时间】:2019-09-28 21:35:01
【问题描述】:

我有一个如下查询:

Select t1.field1
     , sum(t2.field2)
     , sum(t3.field3) 
  from table1 t1
  left 
  join table2 t2 
    on t1.field1 = t2.field1
  left 
  join table3 t3  
    on t2.field1 = t3.field1 
   and t2.date = t3.date
group by t1.field1;

假设表格内容如下所示:

table1:
-field1-
  test
  test1
  test2     

table2:
-field1- -field2- -date-
  test      5       0
  test      4       1
  test      3       2
  test1     3       2

table3:
-field1- -field3- -date-
  test      1       0
  test      2       1
  test      3       2
  test      3       3
  test      3       4
  test      3       5

当我运行查询时,查询会给出结果:

-field1-   -sum(field2)-  -sum(field3)-
  test          24              15
  test1         3              null
  test2        null            null  

这里的问题; sum(field2) 包含来自左连接操作的重复值。我想根据不同 table2 field2 值的总和显示 sum(field2) 。 所以我想得到结果:

-field1-   -sum(field2)-  -sum(field3)-
  test          12              15
  test1         3              null
  test2        null            null  

注意:请不要向我建议派生表选项,因为我知道这可以通过派生表来解决(左联接(从表 3 中选择...按字段 1、字段 2 分组))。

【问题讨论】:

标签: mysql sql optimization


【解决方案1】:

试试下面这个选项-

SELECT A.field1,B.field2,C.field3 
FROM Table1 A
LEFT JOIN (
    SELECT field1,SUM(field2) field2 
    FROM Table2 GROUP BY field1
)B ON A.field1 = B.field1
LEFT JOIN (
    SELECT field1,SUM(field3) field3 
    FROM Table3 GROUP BY field1
)C ON A.field1 = C.field1

【讨论】:

  • 我知道派生表解决方案,但这不是更好的性能方式,所以我没有使用派生表解决方案。
【解决方案2】:

预聚合结果:

select t1.field1, t2.sum2, t3.sum3
from table1 t1 left join
     (select t2.field1, sum(t2.field2) as sum2
      from table2 t2 
      group by t2.field1
     ) t2
     on t1.field1 = t2.field1 left join
     (select t3.field1, sum(t3.field3) as sum3
      from table3 t3 join
           table2 t2
           on t2.field1 = t3.field1 and t2.date = t3.date
      group by t3.field1
     ) t3
     on t3.field1 = t1.field1;

这很棘手,因为date 的条件介于 table2table3 之间。

您指定的期望结果似乎没有考虑date,这在一定程度上简化了逻辑:

select t1.field1, t2.sum2, t3.sum3
from table1 t1 left join
     (select t2.field1, sum(t2.field2) as sum2
      from table2 t2 
      group by t2.field1
     ) t2
     on t1.field1 = t2.field1 left join
     (select t3.field1, sum(t3.field3) as sum3
      from table3 t3
      group by t3.field1
     ) t3
     on t3.field1 = t1.field1;

【讨论】:

  • 您不需要在两个查询中使用最终的group by t1.field1,因为field1 在所有连接表中都是不同的。它只会导致ONLY_FULL_GROUP_BY 错误。
  • @Sha 。 . .使逻辑正确实际上比性能更重要。但是,从性能角度来看,预先聚合表应该是合理的。当然,这取决于您的表结构、硬件和数据库设计。
猜你喜欢
  • 2015-01-10
  • 2021-01-07
  • 2020-03-16
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
相关资源
最近更新 更多