我需要编写一个包含两个外键到另一个表的查询。我需要查看它们并从ID中获取名称。我有一个查询,但我将每个作为单独的记录返回。
SELECT Teams.team_name, Games.ID, Games.game, Games.date, Games.time, Games.team_one, Games.team_two, Games.pts
FROM Teams, Games
WHERE Teams.ID = Games.team_one OR Teams.ID = Games.team_two
ORDER BY Games.ID ASC
所以Games.team_one和Games.team_two是我的Teams表的外键。我需要取回一条记录:
Games.ID,Games.game,Games.date,Games.time,Games.team_one,Games.team_two,Team1 Name,&第二队名称
现在我收到两条相同的记录,但team_name不同。如何为team_one_name和team_two_name创建一个动态字段,以便根据Games.team_one& Games.team_two并将它们作为同一记录的一部分?
感谢您的帮助。
凯文
答案 0 :(得分:1)
使用首选的ANSI样式连接语法:
SELECT t1.team_name AS team_one_name,
t2.team_name AS team_two_name,
games.id,
games.game,
games.date,
games.time,
games.team_one,
games.team_two,
games.pts
FROM games
INNER JOIN teams t1 ON t1.id = games.team_one
INNER JOIN teams t2 ON t2.id = games.team_two
ORDER BY games.id ASC
答案 1 :(得分:0)
我认为你应该使用GROUP BY子句
答案 2 :(得分:0)
只需使用别名以不同的名称加入表团队两次:
SELECT t1.team_name as
team_one_name, t2.team_name as
team_two_name, Games.ID,
Games.game, Games.date,
Games.time, Games.team_one,
Games.team_two, Games.pts
FROM Teams t1, Teams t2, Games
WHERE t1.ID = Games.team_one OR
t2.ID = Games.team_two
ORDER BY Games.ID ASC