在同一个表上具有2列且具有外部标识的表上的SQL查询

时间:2010-04-13 21:09:45

标签: sql

我有一个表格,比如:match(id,hometeam_id,awayteam_id)和team(id,name)。我如何构建我的SQL查询以获得(match_id,hometeam_name,awayteam_name)形式的结果表,因为它们(hometeam_id,awayteam_id)引用同一个表(团队)?

谢谢

4 个答案:

答案 0 :(得分:1)

您只需多次加入团队表:

SELECT m.id, away.name, home.name
FROM match m
INNER JOIN team away ON away.id = m.awayteam_id
INNER JOIN team home ON home.id = m.hometeam_id

答案 1 :(得分:0)

你加入团队表两次。

select matchdate, t1.teamname, t2,teamname from 
match m 
join team t1 on m.hometeamId = t1.teamid
join team t2 on m.awayteamid = t2.teamid

答案 2 :(得分:0)

select m.id, h.name as hometeam_name, a.name as awayteam_name
from match m left join team h on m.hometeam_id = h.id
left join team a on m.awayteam_id = a.id 

答案 3 :(得分:0)

两次加入team表,一次加入主队,再次加入客队,在查询中的表名后面使用别名:

select m.match_id, homeTeam.name as HomeTeamName, awayTeam.name as AwayTeamName
from 
team homeTeam join
match m on m.hometeam_id = homeTeam.hometeam_id join
team awayTeam on awayTeam.hometeam_id = m.awayteam_id