首页 文章

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

提问于
浏览
1

以下是实际发票表

enter image description here

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

而实际的付款表是

enter image description here

基于invoiceID分组后的支付结果集是

enter image description here

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

1 回答

  • 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
    

相关问题