MySQL在同一单元上的多个联接

时间:2019-02-23 01:50:26

标签: mysql sql join

我对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

但是我很确定这段代码是完全错误的。感谢任何帮助。

2 个答案:

答案 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,则可以使用表别名awayTeamhomeTeam访问它。