问题
I have two tables career_types and bookings
career_types
id | name
1 | foo
2 | bar
3 | baz
bookings
id | career_type_id | details
1 | 1 | foo
2 | 1 | bar
3 | 2 | baz
My bookings table has a lot of entries for all career types except career_types.id of 3.
I want a query that will list all my career_types.name's and how many each booking has, and in the case of career_types.id = 1 where there are no bookings for it. I want to return 0.
So far I've been trying variations of
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
And the result I'm looking for is
career_types.name | sum
foo | 2
bar | 1
baz | 0
But at the moment I'm not able to get any output for baz.
回答1:
Aggregate functions only include non-null values in their calculations. In the case of SUM, and most aggregate functions, the result is null if no non-null values are encountered. If zero is needed, rather than null, this can be accounted for simply with:
IFNULL(SUM(x), 0)
来源:https://stackoverflow.com/questions/52174105/keep-zero-values-with-group-by-and-sum-in-mysql