在我的数据库中,uid是autoincrement值表示用户ID,u_follow显示跟随其他用户的用户使用uid分隔的逗号。我想要计算每个用户有多少粉丝。我怎么能这样做?
uid u_follow
1 2,3
2 1,3
3 1,2
4 NULL
5 2,3,4
答案 0 :(得分:4)
每列存储一个值,否则您无法进行关系查询。有关数据库规范化的介绍,请参阅this excellent discussion。
<强> users
强>
uid
...
<强> followers
强>
uid u_follow
1 2
1 3
2 1
2 3
3 1
3 2
5 2
5 3
5 4
然后:
select u_follow, count(*) as num_followers from followers group by u_follow
如果您想要包含没有关注者的用户,请执行以下操作:
with a as (
select u_follow, count(*) as num_followers
from followers group by u_follow
)
select users.uid, coalesce(a.num_followers,0)
from users outer join a on users.uid = a.u_follow