我有兩個表:我怎樣才能做一個查詢選擇嵌套?
// 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
我想選擇的Jack
(id = 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 |
*/
請添加您到目前爲止嘗試過的內容 – Jens
數據結構可能存在問題。您不需要分別存儲1 - > 3和3 - > 1映射。用數據庫中的一條記錄來表示這種關係就足夠了。 – ADyson
重複? http://stackoverflow.com/questions/16513418/how-to-do-the-recursive-select-query-in-mysql – Kostya