使用左外连接加入两个mysql结果集

时间:2012-09-28 06:49:43

标签: mysql sql

以下是实际发票表

enter image description here

根据invoiceID对其进行分组后,结果集为 enter image description here

实际付款表是

enter image description here

以及基于invoiceID分组后的付款结果集

enter image description here

现在我想加入这两个结果集[付款和发票表],并根据InvoiceID查找余额从金额中减去总额,对于非匹配记录,余额列应为零。我试过这个,但没有得到预期的结果。

1 个答案:

答案 0 :(得分:1)

尝试这样的事情,

SELECT  a.InvoiceID,
        a.totalSum InvoiceAmount,
        b.totalSum PaymentAmount,
        a.totalSum - COALESCE(b.totalSum, 0) TotalBalance
FROM
    (
        SELECT  InvoiceID, SUM(Total) totalSum
        FROM    InvoiceTB
        GROUP BY InvoiceID
    ) a LEFT JOIN
    (
        SELECT  InvoiceID, SUM(Total) totalSum
        FROM    paymentTB
        GROUP BY InvoiceID
    ) b
        ON a.InvoiceID = b.InvoiceID