Mysql LEFT JOIN和SUM并显示0而不是NULL

时间:2014-07-10 18:35:42

标签: mysql sum left-join

我有第一个名为“orders”的表和第二个名为“details”的表

orders :
order_id
1
2
3

details :
id | order_id | qty
1  |  1       | 2
2  |  1       | 3

我如何显示如下?

order_id | total
1        | 5
2        | 0
3        | 0

我尝试了这个查询,但没有用:

SELECT *, SUM(qty) AS total
FROM order o
LEFT JOIN details d
  ON o.order_id = d.order_id

2 个答案:

答案 0 :(得分:13)

试试这个:

SELECT o.order_id, IFNULL(SUM(d.qty),0) AS total
FROM orders o
    LEFT JOIN details d ON o.order_id = d.order_id
 GROUP BY order_id

答案 1 :(得分:5)

这将满足您的要求。如果没有明细记录的订单,它会将空值替换为0。

SELECT o.order_id, 
  coalesce(sum(d.qty), 0)
from orders o
left join details d
  on o.order_id = d.order_id
group by o.order_id;

Link to SQL Fiddle Example.