我有几张桌子:

Invoice
-----------------
ID        total
1         500.00
2         100.00
3          10.00

Payment
---------------------------------------
ID    invoiceId     Amount   Method
1        1           400       CASH
2        2            60       CASH
3        2            40      CREDIT


我需要一个查询来获取所有发票,其中至少有一个payment.method是CREDIT,并且该发票的所有付款之和大于发票的总数。

我需要它快。

我怎样才能做到这一点?

最佳答案

SELECT  a.ID InvoiceID,
        a.Total TotalInvoice,
        b.TotalPayment
FROM    Invoice a
        INNER JOIN
        (
            SELECT  InvoiceID, SUM(Amount) TotalPayment
            FROM    Payment
            GROUP   BY InvoiceID
            HAVING  SUM(Method = 'CREDIT') > 0
        ) b ON a.ID = b.InvoiceID AND
                a.Total < b.TotalPayment



SQLFiddle Demo

关于mysql - 如何将查询分组或联接在一起以获取所需的项目列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15960577/

10-11 07:25