SQL多次选择一列

时间:2017-11-27 10:49:22

标签: sql sql-server

所以我有两张桌子:

create table teams(
teamShortName varchar(3) not null,
teamLongName varchar(35) not null,
PRIMARY KEY(teamShortName)
)

create table results(
matchID int identity(1,1)
homeTeam varchar(3) not null references teams(teamShortName),
awayTeam varchar(3) not null references teams(teamShortName),
homeTeamGoals int not null,
awayTeamGoals int not null,
PRIMARY KEY(matchID)
)

现在我想创建一个view / select,它会给我结果但是有teamLongNames ...

尝试了一些东西,但没有成功 - 为主队和客队获得相同的名称/双方的空值

数据看起来像这样

teamShortName     teamLongName
     RMD         FC Real Madrid
     FCB         FC Barcelona

matchID     homeTeam   awayTeam   homeTeamGoals   awayTeamGoals
   1           RMD        FCB           2               2

结果看起来像这样

    Home        HomeGoals        AwayGoals        Away
FC Real Madrid      2                2         FC Barcelona

感谢您帮助我:)

1 个答案:

答案 0 :(得分:2)

使用别名,您可以将表链接两次

SELECT HT.teamLongName, homeTeamGoals, aT.teamLongName, awayTeamGoals
FROM results INNER JOIN teams HT on  homeTeam = HT.teamShortName
INNER JOIN teams AT ON awayTeam = AT.teamShortName