我怎样才能得到朋友的名字?

时间:2017-05-10 10:10:04

标签: mysql sql join

我有两张这样的表:

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

// friends
+-----------+---------+
| friend_id | user_id |
+-----------+---------+
| 2         | 1       |
| 5         | 1       |
| 1         | 3       |
| 2         | 3       |
| 5         | 3       |
| 2         | 4       |
| 1         | 5       |
| 4         | 5       |
+-----------+---------+

这是预期的结果:

+-----------+---------+
| f_name    | u_name  |
+-----------+---------+
| Peter     | John    |
| Jack      | John    |
| John      | Martin  |
| Peter     | Martin  |
| jack      | Martin  |
| Peter     | Barman  |
| John      | Jack    |
| Barman    | Jack    |
+-----------+---------+

我知道,我需要使用JOIN子句。但我不知道我该怎么做呢?

SELECT * FROM friends f
INNER JOIN users u
ON f.friend_id = u.id

我需要另一个JOIN吗?

已编辑:我可以将它们放在同一列中并删除重复项吗?像这样:(我不在乎订单)

+-----------+
| f_name    |
+-----------+
| Peter     |
| Jack      |
| John      |
| Martin    |
| Barman    |
+-----------+

其实我想要一个退出到friendfriend_id列或user_id列)的所有人的名单

1 个答案:

答案 0 :(得分:2)

您可以尝试以下

SELECT u1.name AS f_name, u2.name AS u_name
FROM friends
    INNER JOIN users u1 ON friends.friend_id = u1.id 
    INNER JOIN users u2 ON friends.user_id = u2.id

要获取users中使用的所有friends的名称,您可以使用以下内容:

SELECT DISTINCT name 
FROM users WHERE users.id IN (
    SELECT friend_id FROM friends 
    UNION 
    SELECT user_id FROM friends
)