SQL to get friends AND friends of friends of a user

后端 未结 2 1215
醉话见心
醉话见心 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 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
    

提交回复
热议问题