2013-05-17 35 views
6

我在mySQL中有一個基本的跟隨者/下面的表,看起來像這樣。SQL中的Twitter風格跟隨者跟隨者表

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

我需要的是有一個這樣的系統:

假設我們是用戶B (我們關注用戶A,我們跟隨用戶C和用戶A)

我喜歡返回包含此追隨者/追隨狀態的結果。例如對於用戶B:

id  followedBy  areWeFollowing 
1   userA  1 
2   userC  0 

感謝您的幫助!

arda

回答

2

使用此查詢來查找你是否關注,請關注你。

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

是的!這非常謝謝你,先生。 PS :(有一個錯字「as」) – ardavar

+0

謝謝你的糾正! – ajsanchez22