我有两张桌子:
付款:
id amount type code
1 1200 0 111
2 100 1 111
3 200 0 111
4 50 0 112
5 500 2 112
6 300 3 113
票据:
id details code
-----------------------
1 bill-1 111
2 bill-2 112
3 bill-3 113
4 bill-4 114
我想在amounts
表格中对payments
求和,然后将其加入bills
,如下所示
结果:
bills.code type0Sum type1Sum type2Sum type3Sum
-------------------------------------------------------------------------
111 1400 100 0 0
112 50 0 500 0
113 0 0 0 300
114 0 0 0 0
对不起,如果这是一个新手问题
[编辑]
我使用了类似的查询如下:
SELECT *
FROM bills,
(SELECT SUM(amount) AS type0Sum, code
FROM payments
WHERE type = 0
GROUP BY code)
AS sub1,
(SELECT SUM(amount) AS type1Sum, code
FROM payments
WHERE type = 1
GROUP BY ref_code)
AS sub2
WHERE bills.code = sub1.code
AND bills.code = sub2.code
但我只得到那些 type 的行:
bills.code type0Sum type1Sum type2Sum type3Sum
-------------------------------------------------------
111 1400 100
答案 0 :(得分:0)
我已经修改了最终查询以进行正确的连接,而不是你正在做的旧连接(阅读笛卡尔连接)。给你一个机会,看看它是否有效;
SELECT b.code
,sub1.type0Sum
,sub2.type1Sum
FROM bills b
LEFT JOIN (
SELECT SUM(amount) AS type0Sum
,code
FROM payments
WHERE type = 0
GROUP BY code
) AS sub1 ON b.code = sub1.code
LEFT JOIN (
SELECT SUM(amount) AS type1Sum
,code
FROM payments
WHERE type = 1
GROUP BY ref_code
) AS sub2 ON b.code = sub2.code
还有其他方法可以提高效率,但我会继续查询,以帮助您学习。