2010-05-10 170 views
8

我的MySQL表結構是這樣的。SQL獲取朋友和朋友的朋友

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 

我能得到這個行與單個查詢?

UPDATE ANSWER:我修改了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; 

回答

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 
+0

我嘗試的第一個查詢,但它說,user_id是曖昧 – Enrique 2010-05-10 22:54:06

+0

我將使用第一查詢,第二個給了我錯誤的結果。 非常感謝! – Enrique 2010-05-10 23:54:48

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 
+0

你好,我試過查詢,但它也返回朋友的朋友的朋友。在上面的例子中,它也返回4,5,6,7 – Enrique 2010-05-10 23:03:53

+0

的朋友,我的壞...我試圖避免工會,但這似乎並沒有工作... – a1ex07 2010-05-10 23:31:03

+0

它似乎工作現在... – a1ex07 2010-05-10 23:38:48