MySQL命令加入

时间:2015-04-01 10:24:00

标签: mysql

我将数据库中的事件列表和同一个数据库中的团队列表存储在另一个表中。

info_events

eventid | starttime | hometeam | awayteam

info_teams

teamid | teamname

在info_events表中,hometeam和awayteam都是teamid表的外键。

  SELECT 
      info_events.eventid,  
      info_events.eventdate, 
      info_events.hometeam, 
      info_events.awayteam, 
      info_team.teamname
    FROM 
      info_events 
    INNER JOIN 
      info_teams 
    ON 
      info_events.hometeam = info_teams.teamid

这是我当前的命令并且正在工作,获得家庭团队。我如何在同一命令中获得客队名称?

2 个答案:

答案 0 :(得分:0)

您需要两次加入info_events表,这需要表的唯一别名。

select
ie.eventid,
ie.starttime,
t1.teamname as hometeam,
t2.teamname as awayteam
from info_events ie
join info_teams t1 on t1.teamid = ie.hometeam
join info_teams t2 on t2.teamid = ie.awayteam

如果某些活动可能没有数据进入info_teams,那么您可以使用left join代替inner join

答案 1 :(得分:0)

您可以多次加入表格:

SELECT
    ev.event_id,
    ev.event_date,
    ...
    team1.teamname as home,
    team2.teamname as away
FROM
    info_events ev
JOIN
    info_teams t1 
ON
    ev.hometeam = t1.teamid
JOIN
    info_teams t2
ON
    ev.awaytem = t2.teamid