所以我有两个SQL表。一个表(让我们称之为团队)看起来像:
team_id | team_name
--------|-----------
0 | team_A
1 | team_B
另一张表(称为时间表)如下:
game_id | home_team_id | away_team_id | date
--------|--------------|--------------|-----------
0 | 0 | 1 | 2013-11-05
1 | 1 | 0 | 2013-11-07
如何构建SQL查询以创建类似于
的表home_team | away_team | date
----------|-----------|-----------
Team_A | Team_B | 2013-11-05
Team_B | Team_A | 2013-11-07
我尝试过使用
SELECT schedule.date, teams.team_name AS home_team,
teams.team_name AS away_team
FROM schedule
INNER JOIN teams ON schedule.home_team_id = teams.team_id
INNER JOIN schedule team ON schedule.away_team_id = teams.team_id
但这不会返回任何结果。
答案 0 :(得分:2)
您需要两次加入团队,使用别名来区分:
SELECT schedule.date, ht.team_name AS home_team,
at.team_name AS away_team
FROM schedule
INNER JOIN teams ht ON schedule.home_team_id = ht.team_id
INNER JOIN teams at ON schedule.away_team_id = at.team_id;
答案 1 :(得分:0)
尝试下面的内容 -
SELECT t1.team_name AS home_team,
t2.team_name AS away_team,
schedule.date
FROM schedule
INNER JOIN teams t1 ON schedule.home_team_id = t1.team_id
INNER JOIN teams t2 ON schedule.away_team_id = t2.team_id
order by schedule.date
执行上述你将得到
team_A team_B 2013-11-05
team_B team_A 2013-11-07