2011-04-25 113 views
1

我正在使用以下查詢來獲取每個批次的正確結果。例如,如果我會喜歡看總髮票批2010 ...mysql內部加入羣組

SELECT COALESCE(sum(i.amount),0) AS amount, 
    COALESCE(sum(i.discount),0) AS discount, 
    COALESCE(sum(i.amount) - sum(i.discount),0) AS netpay, 
    b.name AS batch 
FROM fm_batches b 
    INNER JOIN fm_invoices i 
    LEFT JOIN fm_students s ON i.student_id = s.id 
GROUP BY b.name 

而且其輸出結果如下......

| amount | discount | netpay | batch | 
+--------+----------+----------+-------+ 
| 2500 | 500  | 2000  | 2011 | 
+--------+----------+----------+-------+ 
| 2500 | 500  | 2000  | 2010 | 
+--------+----------+----------+-------+ 
| 2500 | 500  | 2000  | 2009 | 
+--------+----------+----------+-------+ 
| 2500 | 500  | 2000  | 2008 | 
+--------+----------+----------+-------+ 

我相信,我在做什麼我的查詢錯誤,因爲它提供了錯誤的結果。它應該返回0,如果沒有找到批2010年。謝謝。

+0

發票和批次之間的關係是什麼......發票表上是否有批次欄? – DRapp 2011-04-25 10:42:43

+0

發票JOIN沒有ON子句。發票和批次/訂閱之間的關係是什麼? – Galz 2011-04-25 10:43:24

+0

@DRapp不,我沒有在發票表上的批次列,但我在訂戶表中,所以表格將訂戶,發票和批次 – seoppc 2011-04-25 10:44:25

回答

2

所以,你需要這樣的東西:

SELECT COALESCE(sum(i.amount),0) AS amount, 
    COALESCE(sum(i.discount),0) AS discount, 
    COALESCE(sum(i.amount)-sum(i.discount),0) AS netpay, 
    b.name AS batch 
FROM batches b 
LEFT JOIN subscribers s on s.bacth_id = b.id 
LEFT JOIN invoices i on i.subs_id = s.id 
GROUP BY b.name 

(猜測用戶和批次之間的關係)。

+0

我沒有在發票表上的batch_id,它在訂戶表上,所以批次與訂戶相關,訂戶與發票相關。 – seoppc 2011-04-25 10:53:19

+0

@seoppc查看我的最新編輯:'s.bacth_id = b.id' – Galz 2011-04-25 10:54:27

+0

我認爲它會正常工作,我會測試它,並將標記此答案,感謝您的幫助。 – seoppc 2011-04-25 10:59:54