2013-04-07 88 views
2

我想創建一個報告,將顯示客戶有一個未解決的帳戶餘額,但我似乎無法得到它使用左連接工作。Mysql左加入總和標準

我有3個表 - 客戶,購買和支付,我想顯示客戶,其採購總額費用少支付大於0

到目前爲止,我有以下查詢:

mysqli_query("SELECT customers.name as name, SUM(purchases.cost) as cost, SUM(payments.paymentamount) as payments FROM customers 
LEFT JOIN purchases ON purchases.customerid = customers.id 
LEFT JOIN payments ON payments.customerid = customers.id 
WHERE (cost - payments) > 0 
GROUP BY customers.id"); 

任何人都可以看到爲什麼這不工作?

感謝您的幫助!

回答

2

您需要計算每個customerID的子查詢上的每個總數,以避免不正確的結果。

SELECT a.*, 
     COALESCE(b.totalPurchase , 0) - COALESCE(c.totalPayment , 0) AS Balance 
FROM customers a 
     LEFT JOIN 
     (
      SELECT customerid, SUM(cost) totalPurchase 
      FROM purchases 
      GROUP BY customerid 
     ) b ON a.ID = b.customerID 
     LEFT JOIN 
     (
      SELECT customerid, SUM(paymentamount) totalPayment 
      FROM payments 
      GROUP BY customerid 
     ) c ON a.ID = c.customerID 
WHERE COALESCE(b.totalPurchase , 0) - COALESCE(c.totalPayment , 0) > 0 
+0

謝謝JW。但是當我嘗試使用while($ row1 = mysqli_fetch_assoc($ q1))顯示結果時,然後$ row1 ['totalPurchase']和$ row1 ['totalPayment']都返回0.任何想法? – mckeegan375 2013-04-07 15:07:46

+0

當客戶沒有來自「採購」表或「付款」表的記錄時,它將返回「0」。你可以提供樣本記錄嗎? ':)' – 2013-04-07 15:10:06

+0

謝謝。我不知道如何發佈片段,但你是正確的 - 在很多情況下,客戶將始終有購買,但可能已經支付任何款項。但是,我的報告顯示所有客戶的採購和付款都爲0,即使他們有兩個實例。謝謝! – mckeegan375 2013-04-07 15:15:47