3

我有一个表用户:

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
4

4 回答 4

3

你需要一个左外连接:

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包括第一个表的每一行,即使它们不存在于连接表中。

于 2012-12-19T15:37:24.567 回答
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
于 2012-12-19T15:47:57.050 回答
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
于 2012-12-19T15:37:49.680 回答
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
于 2012-12-19T15:48:57.550 回答