如何让我的朋友和朋友朋友的朋友?

时间:2011-10-14 12:20:02

标签: mysql sql

我希望得到我的朋友和朋友的朋友,但仅限于2度朋友

我的表结构将是这样的

user_id  friend_user_id
1            2
1            4
2            3
2            4
2            5
3            7

我需要的是,如果我的用户ID为'1',那么我想要所有我的直接朋友(在这种情况下为2& 4)和user_is 2有一些朋友(3,4,5),预期结果为2 ,3,4,5-

我怎么能得到它?

3 个答案:

答案 0 :(得分:3)

SELECT friend_user_id 
FROM table
WHERE user_id = 1 OR user_id IN (SELECT friend_user_id FROM table WHERE user_id = 1) 

答案 1 :(得分:3)

使用union和内部联接:

select friend_user_id from friends
where user_id = ?
union
select f2.friend_user_id from friends f1
join friends f2 on f2.user_id = f1.friend_user_id
where f1.user_id = ?

这应该表现得非常好(比使用子选择要好得多)。

答案 2 :(得分:2)

SELECT friend_user_id FROM friends WHERE user_id = 1
UNION
SELECT friend_user_id FROM friends WHERE user_id IN (SELECT friend_user_id FROM friends WHERE user_id = 1)

这将为您提供一个设置,其中包含id为1的用户的所有朋友和朋友,并删除了重复项。您可以通过使用IN子句嵌套查询来轻松地将此扩展为第3个,第4个等。

相关问题