SELECT teams.teamname AS Home,
teams.teamname AS Away
FROM game
LEFT JOIN teams
ON game.awayteam = teams.teamid
LEFT JOIN teams AS T
ON game.hometeam = T.teamid
我的表格如下
Game
-GameId(Pk,int),
-HomeTeamId (fk,int),
-AwayTeamId(fk,int)
Teams
-TeamId(Pk,int),
-TeamName(Varchar)
我正在尝试在查询中查看主队和客队名。当我加入表时,我的预期结果是主队名和客队名,但是在两个表中只列出了主队名。
Home Team|Spikes
Away Team|Spikes
什么时候应该
Home Team|Spikes
Away Team|Raptors
答案 0 :(得分:1)
您需要让两个加入别名。您正在选择第一次加入的结果两次。
e.g。
SELECT
GameId,
home.TeamName AS Home,
away.TeamName AS Away
FROM Game
LEFT JOIN Teams AS away ON AwayTeamId = away.TeamId
LEFT JOIN Teams AS home ON HomeTeamId = home.TeamId;
答案 1 :(得分:0)
如果将重命名列重命名为联接中的表表达式,则可以使用NATURAL JOIN
并完全避免使用范围变量。另外,我不相信你真的需要外连接:
SELECT Home, Away
FROM game
NATURAL JOIN
( SELECT teamid AS hometeam
teamname AS home
FROM teams ) Home
NATURAL JOIN
( SELECT teamid AS awayteam
teamname AS Away
FROM teams ) away;