我有两张这样的表:
// 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
列)的所有人的名单
答案 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
)