我对SQL很陌生。我已经搜查了几个小时,并且一直困扰着这个问题:
我有一个带有以下键的表games
:
gameID, homeTeamID, awayTeamID
还有具有以下键的表teams
:
teamID, teamName, teamTLC
现在,我想查询一个游戏以及球队名称和球队TLC。我猜查询可能看起来像这样:
SELECT games.id, teams.name
FROM games
WHERE games.homeTeamID = 34 OR games.awayTeamID = 34
INNER JOIN teams AS homeTeam
ON leagueGame.homeTeamID = homeTeam.teamID
INNER JOIN teams AS awayTeam
ON leagueGame.awayTeamID = awayTeam.teamID
但是我很确定这段代码是完全错误的。感谢任何帮助。
答案 0 :(得分:1)
您需要更改顺序。首先,您需要拥有所有数据,然后是您的条件。
'event'
答案 1 :(得分:1)
你还没那么远...:
WHERE
子句位于FROM ... JOIN
部分之后gameID
而不是团队teams
的表别名;您需要使用在JOIN
s中定义的表别名。尝试:
SELECT games.id, homeTeam.name AS homeTeamName, awayTeam.name AS awayTeamName
FROM games
INNER JOIN teams AS homeTeam
ON leagueGame.homeTeamID = homeTeam.teamID
INNER JOIN teams AS awayTeam
ON leagueGame.awayTeamID = awayTeam.teamID
WHERE games.gameID = ?
NB:如果还需要teamTLC
,则可以使用表别名awayTeam
和homeTeam
访问它。