SQL:如何从另一个表中的表中选择不同的值?

时间:2014-10-27 22:28:53

标签: sql sql-server

我有两张桌子

表'团队'有两列

teamID,
teamName

表'匹配'有三列

matchID, 
teamID_1,
teamID_2

...如图所示:

我如何构建一个select语句,根据各自的ID,将Teams.teamName同时传递给Match.teamID_1Match.teamID_2

我只能使用一列或另一列,但不能同时使用两列:

SELECT Match.matchID, Teams.teamName
    FROM Match
    INNER JOIN Teams ON Match.teamID_1 = Teams.teamID

OR

SELECT Match.matchID, Teams.teamName
    FROM Match
    INNER JOIN Teams ON Match.teamID_2 = Teams.teamID

1 个答案:

答案 0 :(得分:4)

您可以多次加入同一个表格。只需将它们设为别名(t1t2,如下所示):

SELECT 
    Match.matchID, 
    t1.teamName, 
    t2.teamName
FROM Match
    INNER JOIN Teams t1 ON Match.teamID_1 = t1.teamID
    INNER JOIN Teams t2 ON Match.teamID_2 = t2.teamID