mysql内连接与group by

时间:2011-04-25 10:36:54

标签: mysql group-by aggregate

我使用以下查询来获取每个批次的正确结果。例如,如果我想查看批次2010的发票总额......

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  |
+--------+----------+----------+-------+

我确信我在查询中做错了,因为它给出了错误的结果。如果批次2010没有找到,它应返回0.谢谢。

1 个答案:

答案 0 :(得分: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

(猜测订阅者和批次之间的关系)。