I have a table users:
user_id name
1 John
2 Dan
3 Jane
4 Sophie
5 Jodie
I then have a table named associates:
user_id assoc_id
1 2
1 3
3 4
3 1
3 5
4 1
5 1
5 2
What I want to do is show how many associates each user has, or none
So, the results would show
user_id Name Number of Associates
1 John 2
2 Dan 0
3 Jane 3
4 Sophie 1
5 Jodie 2
What I’m trying works but does not show those with 0
Here’s what I’m trying, how do I get the 0s?
SELECT u.user_id, u.name, count(a.user_id) as howmany from users u
join associates a on a.user_id = u.user_id
group by u.user_id order by u.user_id asc
You need a LEFT OUTER JOIN:
The
LEFT OUTER JOINwill include every rows of the first table even is they aren’t present in the joined table.