【发布时间】:2018-09-05 05:44:43
【问题描述】:
我有两张表 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 获得任何输出。
【问题讨论】:
-
你应该使用
COUNT而不是SUM -
我应该更改上面的示例,在我的实际应用程序中,预订字段可以是任何数字。这是我需要总结的数字
-
是的,这个例子在这方面令人困惑。但是您的查询看起来不错。
-
查询按预期工作sqlfiddle.com/#!9/246144/1