Twitter style following-follower table in SQL

自古美人都是妖i 提交于 2020-01-01 09:36:06

问题


I have a basic follower/following table in mySQL which looks like this.

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

I checked these topics but couldnt find what I need

database design for 'followers' and 'followings'?

SQL Following and Followers

What I need is to have a system like this:

Assume we are userB ( we follow userA, we are followed by userC and userA)

I like to return a result that includes this follower/following state. For example for userB:

id      followedBy     areWeFollowing
1           userA       1
2           userC       0

Thanks for your help!

arda


回答1:


With this query to find if who you follow, follow you too.

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';


来源:https://stackoverflow.com/questions/16618631/twitter-style-following-follower-table-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!