如何进行选择嵌套的查询?

时间:2017-01-31 15:53:07

标签: mysql sql join

我有两张桌子:

// 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         |
*/

2 个答案:

答案 0 :(得分:2)

添加一个IN子句,所有Jack的朋友都使用不同的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);

答案 1 :(得分: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)