【发布时间】: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 分组))。
【问题讨论】:
-
检查这个答案以获得一个hacky(但有效的方法):stackoverflow.com/a/52474658/2469308
-
如何测试
SUM(field3)给15?我得到 12 个有重复项和 6 个没有重复项 -
另一种方法是使用Correlated Subqueries,就像在这个答案中一样:stackoverflow.com/a/52474822/2469308
-
派生表有什么问题?
-
提供db-fiddle.com 示例和您正在尝试的查询,因为您当前的 ascii 数据示例无法在工具中用于重现您的问题或问题..
标签: mysql sql optimization