SQL中的Twitter样式跟随者表

时间:2013-05-17 22:09:46

标签: sql database twitter-follow

我在mySQL中有一个基本的关注者/关注表,看起来像这样。

id      user_id     follower_id
1           userA       userB
2           userC       userA
3           userA       userC
4           userB       userC
5           userB       userA

我查看了这些主题,但无法找到我需要的内容

database design for 'followers' and 'followings'?

SQL Following and Followers

我需要的是拥有这样的系统:

假设我们是userB(我们关注userA,我们跟着userC和userA)

我想返回包含此关注者/关注状态的结果。例如对于userB:

id      followedBy     areWeFollowing
1           userA       1
2           userC       0

感谢您的帮助!

阿尔达

1 个答案:

答案 0 :(得分:3)

使用此查询查找您关注的人,也请关注您。

SELECT ff1.follower_id as followedBy,
(
   select count(follower_id) 
   from follower_following as ff2 
   where ff2.user_id = ff1.follower_id 
   and ff2.follower_id = ff1.user_id 
) as areWeFollowing 
FROM follower_following as ff1  
where user_id = 'userB';