使用内部连接两次

时间:2015-01-09 10:24:07

标签: sql sql-server select join inner-join

尝试选择匹配表并将ID转换为学校名称,但是现在我一次只能运行一行。我的选择会是什么样的呢?

select Match.ID, School, GuestTeamID from Match
inner join Team on team.id = match.HomeTeamID

匹配表

+------------+------------+-------------+
|         ID | HomeTeamID | GuestTeamID |
+------------+------------+-------------+
|          1 |          1 |           2 |
|          2 |          3 |           4 |
+------------+------------+-------------+

团队表:

+----+----------+
| ID |  School  |
+----+----------+
|  1 | School A |
|  2 | School B |
|  3 | School C |
|  4 | School D |
+----+----------+

1 个答案:

答案 0 :(得分:4)

使用匹配表两次加入Team表以获取学校名称。

试试这个:

SELECT M.ID, t1.School AS HomeSchool, t2.School AS GuestSchool
FROM MATCH m 
INNER JOIN Team t1 ON t1.id = m.HomeTeamID
INNER JOIN Team t2 ON t2.id = m.GuestTeamID;