我有两个这样的表:
// 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 |
+-----------+
其实我想要一个退出
friend
表的所有人的名单(friend_id
列或user_id
列) 最佳答案
您可以尝试以下
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
)