来自两个表的两列的总和 - MySQL

时间:2015-03-12 06:04:22

标签: mysql

我有三张桌子

t1
CustId    Name
1         XYZ
2         PQR

t2
CustId    Income
1         100
1         200
2         50
2         100

t3
CustId   Expense
1        50
1        70
2        30
2        40

我需要运行一个查询,我得到以下结果

CustId    Total Income     Total Expense
1         300              120
2         150              70

我尝试了普通的SUM和Group By,但结果与预期的......

非常不同

我尝试的查询是

SELECT t1.custid, SUM(t2.Income), SUM(t3.Expense) FROM t1
LEFT JOIN t2 ON t1.custId = t2.CustId
LEFT JOIN t3 ON t1.CustId = t3.CustId
GROUP BY t1.CustId

你会感激的任何帮助......

3 个答案:

答案 0 :(得分:1)

尝试对所有三个表进行内连接,然后按客户ID对结果进行分组,如:

SELECT t1.custId, SUM(t2.Income), SUM(t3.expense)
FROM t1 INNER JOIN t2
ON t1.custId = t2.custId
INNER JOIN t3
ON t2.custId = t3.custId
GROUP BY t1.custId

答案 1 :(得分:1)

尝试以下查询。

SELECT t1.CustID, IFNULL(tbl1.Income,0) AS 'TotalIncome', IFNULL(tbl2.Expenses,0) AS 'TotalExpenses' 
FROM t1
LEFT JOIN (SELECT t2.CustID,SUM(Income) AS 'Income' FROM t2 GROUP BY t2.CustID) tbl1
ON t1.CustID = tbl1.CustID
LEFT JOIN (SELECT t3.CustID,SUM(Expenses) AS 'Expenses' FROM t3 GROUP BY t3.CustID) tbl2
ON t1.CustID = tbl2.CustID;

SQL小提琴:http://sqlfiddle.com/#!9/ad05d/8

答案 2 :(得分:0)

您可以使用以下查询来实现您的目标

SELECT t1.custid, ti.Income, te.expense FROM t1 LEFT JOIN (select t2.custId, sum(t2.Income) as income from t2 group by t2.custId) as ti ON t1.custId = ti.CustId LEFT JOIN (select t3.custId, sum(t3.Expense) as expense from t3 group by t3.custId) as te ON t1.CustId = te.CustId

至于为什么您以前的查询无效。我可以给出以下解释。

在SQL中,当您进行连接时,数据库内部生成所有条目的笛卡尔积,并根据返回数据的where子句。所以当你做到了

SELECT t1.custid, SUM(t2.Income), SUM(t3.Expense) FROM t1 LEFT JOIN t2 ON t1.custId = t2.CustId

你有4行,其中customerId在行中重复,现在当你通过在customerId上应用相同条件来加入t3表时,数据库将能够匹配两个记录中的customerID,因此你得到8行。这就是你的查询无效的原因