我有一个包含两列的表,每列包含一个成员标识,该标识是包含其名称的成员表的外键。我想选择第一个包含名称而不是成员ID的表。我不知道如何做到这一点。我觉得肯定有一种涉及INNER JOIN的方法,但我想不出如何在一个INNER JOIN中从一个表中选择两个名字。有什么想法吗?
提前致谢!
匹配表
|------|-------|
| user | match |
|------|-------|
| 1 | 4 |
| 2 | 1 |
| 3 | 2 |
|------|-------|
会员表
|------|-------|
| user | name |
|------|-------|
| 1 | Joe |
| 2 | Kyle |
| 3 | John |
| 4 | Nate |
|------|-------|
期望的输出
|------|-------|
| user | match |
|------|-------|
| Joe | Nate |
| Kyle | Joe |
| John | Kyle |
|------|-------|
答案 0 :(得分:3)
你应该加入成员表两次。
SELECT M1.NAME , M2.NAME
FROM MEMBERS M1
INNER JOIN MATCH M
ON M1.USER = M.USER
INNER JOIN MEMBERS M2
ON M2.USER = M.MATCH
如果您的数据库是mysql,请注意较低和较高的标识符。
答案 1 :(得分:2)
您也可以使用外部申请:http://sqlfiddle.com/#!3/8f932/5
执行此操作SELECT me.name as 'User',
mem.name as 'Match'
FROM Match m
OUTER APPLY(
SELECT me.name
FROM Members me
WHERE me.id = m.match
)mem
LEFT JOIN Members me on me.id = m.id
或者:http://sqlfiddle.com/#!3/8f932/6
SELECT me.name as 'User',
mem.name as 'Match'
FROM Match m
LEFT JOIN Members mem on mem.id = m.match
LEFT JOIN Members me on me.id = m.id
答案 2 :(得分:0)
你可以做两个连接:
SELECT u1.name, u2.name
FROM members u1
INNER JOIN match m
ON u1.user = m.user
INNER JOIN members u2
ON u2.user = m.match