首页 > 解决方案 > 在 mysql 中使用 GROUP BY 和 SUM 保持零值

问题描述

我有两张表 career_types 和 bookings

职业类型

id | name
1 | foo
2 | bar
3 | baz

预订

id | career_type_id | details
1 | 1 | foo
2 | 1 | bar
3 | 2 | baz

我的预订表有很多针对所有职业类型的条目,除了 career_types.id 为 3。

我想要一个查询,其中将列出我所有的 career_types.name 以及每个预订有多少,并且在 career_types.id = 1 的情况下没有预订。我想返回 0。

到目前为止,我一直在尝试

SELECT career_types.name, sum(bookings.id)
FROM career_types
LEFT JOIN bookings ON (career_types.id = bookings.career_type_id)
GROUP BY career_types.id

我正在寻找的结果是

career_types.name | sum
foo | 2
bar | 1
baz | 0

但目前我无法为 baz 获得任何输出。

标签: mysqljoingroup-bysum

解决方案


聚合函数仅在其计算中包含非空值。对于 SUM 和大多数聚合函数,如果没有遇到非空值,则结果为空。如果需要零,而不是 null,这可以简单地解释为: IFNULL(SUM(x), 0)


推荐阅读