tags:

views:

174

answers:

2

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;
+2  A: 

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
DVK
I tried the first query but it says that user_id is ambiguous
Enrique
I'll use the first query, the second one gave me wrong results.Thank you very much!
Enrique
+1  A: 
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
a1ex07
Hello I tried the query but it also returns the friends of friends of friends. In the above example it also returns the friends of 4,5,6,7
Enrique
yep, my bad... I've tried to avoid union, but that doesn't seem to be working...
a1ex07
It seems to work now...
a1ex07
Thank you. Now it works!! and this one seems to be more efficient than the one with the UNION
Enrique