查询两个表的总和
我有一个交易表和一张付款表。我需要在Trans Table和Payment Table上获得总金额,并且它必须由TransID分组。我希望有人可以帮我找到正确的sql语句。
我尝试了下面的sql但是Trans Table上的金额总和将乘以Payment表上相同TransID的记录数。
-> Select Trans.TransID, sum(Trans.Amount), sum(Payment.Amount)
from Trans
Left Join Payment on Payment.TransID = Trans.TransID
我也尝试了下面的sql,但与上面的sql语句相比,处理时间更长。
-> Select TD.TransID, TD.Amt, PD.paid
from
(
Select Trans.TransID, Sum(Trans.Amount) AS Amt
from Trans Group By Trans.TransID
) AS TD
Left Join
(
Select Payment.TransID, sum(Payment.Amount) AS Paid
from payment
Group by Payment.TransID
) AS PD On PD.TransID = TD.TransID
Trans Table
TransID | Amount
T1 | 10
T2 | 15
T3 | 12
T4 | 20
T5 | 11
T1 | 15
T5 | 14
----------
付款表
TransID | Amount
T1 | 5
T3 | 10
T1 | 3
T2 | 5
T5 | 10
----------
我需要的查询结果应该是这样的:
TransID | Amount | Paid
T1 | 25 | 8
T2 | 15 | 5
T3 | 12 | 10
T4 | 20 | 0
T5 | 25 | 10
答案 0 :(得分:1)
您可以使用两个不同的查询,一个对所有Amounts进行求和(并将Paid列设置为0),另一个对所有Paid值求和(并将Amount列设置为0)并使用UNION ALL查询和SUM进行组合结果:
SELECT TransID, SUM(Amount) AS Amount, SUM(Paid) AS Paid
FROM (
SELECT TransID, SUM(Amount) AS Amount, 0 AS Paid
FROM Trans
GROUP BY TransID
UNION ALL
SELECT TransID, 0 AS Amount, SUM(Amount) AS Paid
FROM Payment
GROUP BY TransID
) s
GROUP BY TransID
请查看小提琴here。
答案 1 :(得分:0)
就处理时间而言,如果您有“付款(转账,金额)
的索引,则以下内容可能最快SELECT t.TransId, t.Amount,
(SELECT SUM(p.Amount)
FROM Payment p
WHERE p.TransId = t.TransId
) as Paid
FROM (SELECT t.TransID, SUM(t.Amount) AS Amount
FROM Trans t
GROUP BY t.TransID
) t;
MySQL将利用相关子查询的索引,该索引应该比三个group by
查询更快。