2017-01-31 89 views
0

我有兩個表:我怎樣才能做一個查詢選擇嵌套?

// users 
+----+--------+ 
| id | name | 
+----+--------+ 
| 1 | Jack | 
| 2 | Peter | 
| 3 | John | 
| 4 | Barman | 
| 5 | Ali | 
+----+--------+ 

// friends 
+---------+-----------+ 
| user_id | friend_id | 
+---------+-----------+ 
| 1  | 3   | 
| 1  | 4   | 
| 1  | 5   | 
| 3  | 1   | 
| 3  | 2   | 
| 3  | 4   | 
| 5  | 2   | 
+---------+-----------+ 
-- both user_id and friend_id columns refer to the id column of users table 

我想選擇的Jackid = 1所有的朋友。所以這裏是查詢:

select * from friend where user_id = 1 
/* output 
| 1  | 3   | 
| 1  | 4   | 
| 1  | 5   | 
*/ 

現在我還想選擇朋友Jack的朋友。我怎樣才能做到這一點?


請注意,我不想選擇重複的行。所以,我想這樣的輸出:

/* expected output: 
| 1  | 3   | 
| 1  | 4   | 
| 1  | 5   | 
| 3  | 2   | 
| 3  | 4   | 
| 5  | 2   | 
*/ 
+1

請添加您到目前爲止嘗試過的內容 – Jens

+0

數據結構可能存在問題。您不需要分別存儲1 - > 3和3 - > 1映射。用數據庫中的一條記錄來表示這種關係就足夠了。 – ADyson

+0

重複? http://stackoverflow.com/questions/16513418/how-to-do-the-recursive-select-query-in-mysql – Kostya

回答

2

添加IN子句與傑克的所有朋友使用不同的USER_ID,friend_id

select distinct f1.user_id, f1.friend_id 
from friend f1 
where user_id = 1 
     or 
     user_id in (select f2.friend_id 
        from friend f2 
        where user_id = 1); 
+0

爲什麼會被低估? 'by by'組是不必要的,但是很難確定是否存在倒計時。 –

+0

謝謝.. uvpote – stack

+1

f2.friend應該是f2.friend_id – lud1977

1
select distinct 
    f2.* 
from 
    friend f1, 
    friend f2 
where 
    f1.user_id = 1 and 
    (f1.friend_id = f2.user_id or f2.user_id = 1) 

這仍然包括重複與相反方向(它認爲A--朋友 - > B與B不同 - 朋友 - > A)

+0

謝謝..upvote – stack

相關問題