mysql连接2个表 - 但必须连接两次相同的表

时间:2017-06-17 21:46:01

标签: mysql join

我正为我的联赛制作一个垒球赛程表。我有一个TEAMS表和一个GAMES表。 TEAMS是id&队名。 GAMES表有日期,时间,home_team(与TEAMS表id相关)和away_team(与TEAMS表id相关)。

我想从GAMES表中选择所有游戏,但不是home_team和away_team显示团队的ID,我希望它显示TEAMS表中的team_name。

这是我的查询,但有问题...

SELECT games.date, games.time, games.home_team, 
games.away_team, teams.team_name FROM games JOIN teams ON games.home_team=teams.id 
JOIN teams on games.away_team=teams.team;
  

1066 - 不是唯一的表/别名:团队

3 个答案:

答案 0 :(得分:0)

是的,因为你必须提供不同的表别名,因为你要加入同一个表两次,如

openssl x509

答案 1 :(得分:0)

您需要使用表别名。所以,你会有这样的事情:

SELECT games.date, games.time, games.home_team, games.away_team, teams1.team_name 
FROM games 
   JOIN teams AS teams1 ON games.home_team=teams1.id 
   JOIN teams AS teams2 ON games.away_team=teams2.team;

答案 2 :(得分:0)

WOOHOO我得到它!!!!!这里需要列别名和表别名!!!!!!我不敢相信我做到了!

SELECT g.day,g.date,g.time,t.team_name AS away_team,t2.team_name AS home_team 来自GAMES as g 加入团队作为远离at_team = t.id 在t = home_team = t2.id

上加入队伍