我有一个表用户:
user_id name
1 John
2 Dan
3 Jane
4 Sophie
5 Jodie
然后我有一个名为associates的表:
user_id assoc_id
1 2
1 3
3 4
3 1
3 5
4 1
5 1
5 2
我想要做的是显示每个用户有多少个员工,或者没有
所以,结果会显示
user_id Name Number of Associates
1 John 2
2 Dan 0
3 Jane 3
4 Sophie 1
5 Jodie 2
我正在尝试的是什么,但没有显示那些0
这是我正在尝试的,我如何获得0?
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
答案 0 :(得分:3)
你需要LEFT OUTER JOIN:
SELECT u.user_id, u.name, count(a.user_id) as howmany
FROM users u LEFT OUTER JOIN associates a
ON a.user_id = u.user_id
GROUP BY u.user_id
ORDER BY u.user_id ASC
LEFT OUTER JOIN
将包括第一个表的每一行,即使它们不在连接表中。
答案 1 :(得分:1)
试试这个:
SELECT u.user_id,
u.name,
count(a.user_id) as howmany
FROM users u
LEFT OUTER JOIN associates a
ON a.user_id = u.user_id
GROUP BY u.user_id
ORDER BY u.user_id ASC
答案 2 :(得分:0)
尝试使用左连接而不是内连接,这应该选择没有相应关联的行。
SELECT u.user_id, u.name, count(a.user_id) as howmany
from users u
left join associates a
on a.user_id = u.user_id
group by u.user_id
order by u.user_id asc
答案 3 :(得分:0)
这也适用于严格的规则(如果我没有做过任何错字):
SELECT users.*, ISNULL(associatesCount.AssocCount, 0) AS AssocCount
FROM users
LEFT JOIN (
SELECT user_id, COUNT(*) AS AssocCount
FROM associates
GROUP BY user_id
) AS associatesCount
ON users.user_id = associatesCount.user_id