MySQL - 在单独的列中显示两个内部联接

时间:2016-03-16 14:08:22

标签: mysql sql database join inner-join

首先,我有这个返回所有足球比赛的日期

HomeShotsOnTarget(HST)= FullTimeHomeGoals(FTHG)

AwayShotsOnTarget(AST)= FullTimeAWayGoals(FTHG)

SELECT MatchDate, HomeTeam, AwayTeam 
FROM matches 
WHERE HST=FTHG or AST=FTAG

显示

MatchDate | HomeTeam | AwayTeam
2003/08/23    17          32
2003/09/13    24          39

依旧等......

HomeTeam和AwayTeam下的数字是TeamCodes,它们在另一个名为club的表中,也有团队的真名。

以下内容将HomeTeam的TeamCode与表俱乐部中的RealName相匹配。

SELECT MatchDate, RealName
FROM club T1 
INNER JOIN matches T2 ON T1.TeamCode = T2.HomeTeam

显示

MatchDate|  RealName|
2003/08/23  Arsenal
2003/09/13 Blackburn

等等...

所以我的问题是我似乎找不到在HomeTeam和AwayTeam下显示RealName而不是TeamCode的方法。像这样......

MatchDate | HomeTeam | AwayTeam
2003/08/23   Arsenal   Aston Villa
2003/09/13   Blackburn  Man Utd

3 个答案:

答案 0 :(得分:1)

可能是这样的:

SELECT MatchDate, homeTeam.RealName AS HomeTeam, awayTeam.RealName AS AwayTeam
FROM matches m
INNER JOIN club homeTeam ON (m.HomeTeam = homeTeam.TeamCode)
INNER JOIN club awayTeam ON (m.AwayTeam = awayTeam.TeamCode);

我用来放置一些含义标签,而不仅仅是T1T2

答案 1 :(得分:0)

你只需要另外加入Away Team的俱乐部牌桌,就像这样:

SELECT MatchDate, T1.RealName AS HomeTeamName, T3.RealName AS AwayTeamName 
FROM club T1 
INNER JOIN matches T2 ON T1.TeamCode = T2.HomeTeam 
INNER JOIN club T3 ON T3.TeamCode = T2.AwayTeam

答案 2 :(得分:0)

您只需加入Team-Table两次,请尝试以下查询:

SELECT 
  MatchDate, 
  T1.RealName, 
  T2.RealName 
FROM 
  matches INNER JOIN club T1 ON (matches.HomeTeam = T1.TeamCode)
          INNER JOIN club T2 ON (matches.AwayTeam = T2.TeamCode)
WHERE 
  HST=FTHG OR AST=FTAG