2013-02-16 97 views
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正在被服務的每個發票的數量成倍增加。

有沒有辦法用一個查詢來提取所有數據?

回答

0

你有兩個子表,它們各自的連接返回不同數量的行。如果沒有分組/組合運行查詢,你結束了:

+------+-----------+-------+-----------+--------+ 
| id | serviceid | price | paymentid | amount | 
+------+-----------+-------+-----------+--------+ 
| 1 |   1 | 5.00 |   1 | 7.00 | 
| 1 |   1 | 10.00 |   1 | 7.00 | 
| 2 |   2 | 20.00 |   2 | 12.00 | 
| 2 |   2 | 20.00 |   2 | 8.00 | 
+------+-----------+-------+-----------+--------+ 

注意如何支付的金額$ 7重複發票#1和服務價格的發票#2。 MySQL試圖填充查詢結構產生的「漏洞」,通過從具有較少行的表中複製值來填充。

對於這種類型的查詢工作,你需要使用corelated子查詢,使每個子查詢可以做自己的總結,而不受其他表的行數限制的約束:

select invoices.id, 
    (select sum(price) from services where services.iid = invoices.id) AS service_price, 
    (select sum(amount) from payments where payments.iid = invoices.id) AS payment_amount 
FROM invoices; 

產生

+------+---------------+----------------+ 
| id | service_price | payment_amount | 
+------+---------------+----------------+ 
| 1 |   15.00 |   7.00 | 
| 2 |   20.00 |   20.00 | 
+------+---------------+----------------+ 
+0

謝謝!這工作。 – user1218595 2013-02-17 00:00:36

+0

是否有可能採取這一步,並只選擇payment_amount user1218595 2013-02-17 00:01:25

+0

當然,只需在查詢中添加'having'子句:'...從具有payment_amount 2013-02-17 03:12:42