mysql - 在 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 获得任何输出。
解决方案
聚合函数仅在其计算中包含非空值。对于 SUM 和大多数聚合函数,如果没有遇到非空值,则结果为空。如果需要零,而不是 null,这可以简单地解释为:
IFNULL(SUM(x), 0)
推荐阅读
- c - 将二进制结构写入文件,意外结果?
- javascript - 从对象数组创建一个字符串
- c# - UWP:某些特定目标机器的异常“ClassFactory 无法提供请求的类”
- php - 在 php 中使用 foreach 语句管理 4 维数组或 5 维数组
- c# - 在 Unity 中使用鼠标移动刚体的问题
- python - 遍历数据框中的所有行并检查所有列值是否在列表中
- jquery - 用于显示消息的 CSS
- .htaccess - 301 重定向可能与 CloudFlare 冲突
- java - 如何在多线程环境中实现 FIFO 队列
- arrays - Partials wrt 单个数组,其中数组的两个不同部分用于计算?