Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to get friends AND friends of friends of a user

Tags:

sql

mysql

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 insert 2 records in FRIEND_LIST. If user 1 is friend of user 2 then the next rows are inserted into FRIEND_LIST

1,2
2,1

I want to get the friends and friends of friends of an specific user.

The select should return columns 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

Then the query to get 1's friends and friends of friends should return:

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

Can I get this rows with a single query?

UPDATE ANSWER: I modified DVK's answer a little bit and this is the query that returns what I was looking for.

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;
like image 612
Enrique Avatar asked May 10 '10 22:05

Enrique


2 Answers

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
like image 58
a1ex07 Avatar answered Nov 13 '22 15:11

a1ex07


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
like image 32
DVK Avatar answered Nov 13 '22 16:11

DVK