0
總和我有3個表MySQL的選擇了從一個表與其他2個表
發票:ID,客戶
服務:invioce_id,價格
付款:INVOICE_ID,量
我想要選擇所有服務價格均爲amountDue且任何付款金額爲每張發票的amountPaid的所有發票。
因此,舉例來說,如果我有以下行:
發票
id = 1, client = 232
id = 2, client = 535
服務
invoice_id = 1, price = 5.00
invoice_id = 1, price = 10.00
invoice_id = 2, price = 20.00
支付
invoice_id = 1, amount = 7.00
invoice_id = 2, amount = 12.00
invoice_id = 2, amount = 8.00
我想對所有發票結果查詢行是這樣的:
發票
id = 1, client = 232, amountDue = 15.00, amountPaid = 7.00
id = 2, client = 535, amountDue = 20.00, amountPaid = 20.00
我有這樣的查詢:
SELECT invoices.*,
sum(services.price) AS amountDue,
sum(payments.amount) AS amountPaid
FROM invoices
LEFT JOIN services ON services.invoice = invoices.id
LEFT JOIN payments ON invoices.id = payments.invoice
GROUP BY invoices.id
但由此產生的amountPaid正在被服務的每個發票的數量成倍增加。
有沒有辦法用一個查詢來提取所有數據?
謝謝!這工作。 – user1218595 2013-02-17 00:00:36
是否有可能採取這一步,並只選擇payment_amount
user1218595
2013-02-17 00:01:25
當然,只需在查詢中添加'having'子句:'...從具有payment_amount
2013-02-17 03:12:42