开发者

MYSQL Selecting reciprocating data?

I have a table called Follow, with three fields:

  • Id (autoincrement int),
  • UserId (int),
  • Following (int)

If I have data like this:

ID    UserId    Following   
--------------------------
1       2          3
2       3          2
3       2          5
4       2          6
5       3          5

How would I find user 2's friends (ie: user 2 is following them,开发者_C百科 and they follow user 2)

I guess, in other words, if user 'a' follows user 'b', and user 'b' follows user 'a', how do I select user A ??


Try this:

SELECT a.UserId, a.Following
  FROM Follow a INNER JOIN Follow b
    ON a.UserId = b.Following
   AND b.UserId = a.Following


select f1.UserId
from Follow f1
join Follow f2 on f2.Following = f1.UserId and f2.UserId = f1.Following
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜