SQL to get friends AND friends of friends of a user

后端 未结 2 1216
醉话见心
醉话见心 2021-02-03 12:56

My MySQL tables structure is like this.

USER
int id
varchar username

FRIEND_LIST
int user_id
int friend_id

For each friend relationship I inse

相关标签:
2条回答
  • 2021-02-03 13:58
    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
    
    0 讨论(0)
  • 2021-02-03 14:02

    This is less efficient but readable:

    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
    
    0 讨论(0)
提交回复
热议问题