我试图弄清楚为什么联接会带来它所带来的结果。
这是一个简单的测试我正在努力。
我有两个表:Table1和Table2。
表1
-------------------
id name amount
---------------------
1 | Fred | 2
3 | Fred | 3
5 | Fred | 4
2 | Hellen | 3
4 | Hellen | 3
6 | Hellen | 3
表2
-------------------
id name amount
---------------------
1 | Fred |4
2 | Hellen |3
3 | Paul |3
4 | Fridah |5
当我使用以下声明时
SELECT p.name,sum(p.amount) as amount FROM `table1` as p
left join table2 as c on p.name = c.name GROUP BY c.name , p.name
我得到了这个结果
---------------
name amount
---------------
Fridah | 5
Paul | 3
Fred | 12
Hellen | 9
但这真的很奇怪。我想从table1中得到amount
的总和,但是联接给了我两个表的总和。为什么是这样?
答案 0 :(得分:1)
更改group by
子句,仅包含p.name
GROUP BY p.name
,如下所示。在这里查看演示小提琴http://sqlfiddle.com/#!2/6c0e3/1
SELECT p.name,sum(p.amount) as amount
FROM `table1` as p
left join table2 as c on p.name = c.name
GROUP BY p.name
结果
NAME AMOUNT
Fred 9
Hellen 9
修改强>
您可以单独计算总和,然后加入派生表,以便从两个表中获得正确的总和,如下所示。请参阅更新小提琴Here
select X.name,X.amount,Y.amount2
from
(
select name,sum(amount) as amount
from table1
group by name
) X
left join
(
select name,sum(amount) as amount2
from table2
group by name
) Y on X.name = Y.name
结果:
NAME AMOUNT AMOUNT2
Fred 9 4
Hellen 9 3
答案 1 :(得分:1)
这是您的查询:
SELECT p.name, sum(p.amount) as amount
FROM `table1` as p left join
table2 as c
on p.name = c.name
GROUP BY c.name , p.name;
您的结果表明您正在运行的查询是:
SELECT p.name, sum(c.amount) as amount
-------------------^
FROM `table1` as p left join
table2 as c
on p.name = c.name
GROUP BY c.name , p.name;
如果您运行正确的查询,您将获得预期的结果。
编辑:
正确的查询如下:
SELECT c.name, sum(p.amount) as amount
FROM table2 as c left join
table1 as p
on p.name = c.name
GROUP BY c.name;
答案 2 :(得分:-1)
我找到了答案。 通过向求和的列添加不同,我能够得到正确的结果。 看看http://sqlfiddle.com/#!2/6c0e3/12/0
谢谢大家的帮助。