SQL获取用户朋友和朋友的朋友

时间:2010-05-10 22:27:04

标签: sql mysql

我的MySQL表格结构是这样的。

USER
int id
varchar username

FRIEND_LIST
int user_id
int friend_id

对于每个朋友关系,我在FRIEND_LIST中插入2条记录。 如果用户1是用户2的朋友,则下一行将插入FRIEND_LIST

1,2
2,1

我希望得到特定用户朋友的朋友和朋友。

select应返回a,b,c列。

a: user_id
b: friend_id
c: username (username of friend_id )

If 1 is friend of 2 and 3.
2 is friend of 3, 4 and 5
3 is friend of 5,6,7

然后查询以获得1的朋友和朋友的朋友应该返回:

1 2 two
1 3 three
2 1 one
2 3 three
2 4 four
2 5 five
3 1 one
3 5 five
3 6 six
3 7 seven

我可以使用单个查询获取此行吗?

更新答案:我稍微修改了DVK的答案,这是返回我要查找内容的查询。

SELECT friends.user_id, friends.friend_id, username

FROM
      FRIEND_LIST friends, USER

WHERE
      CAT_USER.id = friends.friend_id
AND
      friends.user_id = 1

UNION

SELECT
        fof.user_id, fof.friend_id, username
FROM
        FRIEND_LIST friends, FRIEND_LIST fof, USER
WHERE
        USER.id = fof.friend_id
 AND
        friends.friend_id = fof.user_id
 AND
        friends.user_id = 1;

2 个答案:

答案 0 :(得分:2)

SELECT f1.user_id, f1.friend_id FROM
friends_info f1
WHERE f1.user_id = 1 OR
f1.user_id IN
(
 select f2.friend_id
 from friends_info f2
 where f2.user_id = 1
)
 ORDER BY user_id

答案 1 :(得分:1)

效率低但可读:

SELECT friends.user_id, friends.friend_id, username 
FROM FRIEND_LIST friends, USER
WHERE USER.id           = friends.friend_id
 AND  USER.id = 1
UNION

SELECT USER.user_id, fof.friend_id, username 
FROM FRIEND_LIST friends, FRIEND_LIST fof, USER
WHERE USER.id           = fof.friend_id
 AND  friends.friend_id = fof.user_id
 AND  USER.id = 1

OR

SELECT user_id, f_fof.friend_id, username 
FROM USER, (
    SELECT f.user_id, f.friend_id
    FROM   FRIEND_LIST f
    WHERE  user_id = 1
    UNION
    SELECT f.user_id, fof.friend_id
    FROM   FRIEND_LIST f, FRIEND_LIST fof
    WHERE  user_id = 1
     AND   f.friend_id = fof.user_id
) as f_fof
WHERE USER.id           = f_fof.friend_id