在连接中显示名称而不是ID

时间:2017-07-23 01:37:14

标签: sql mysqli

我正在尝试加入,我无法显示我想要的内容。

这是我目前的代码。

SELECT
   Tournaments.TourneyDate, 
   Tournaments.TourneyLocation, 
   Tourney_Matches.OddLaneTeamID, 
   Tourney_Matches.EvenLaneTeamID
FROM
   Tournaments
INNER JOIN Tourney_Matches ON (Tournaments.TourneyID = Tourney_Matches.TourneyID);

输出Dates,Location,OddLaneIDs和EvenLaneIDs。

而不是最后两列放置原始ID,我需要它们来显示ID的相关团队名称。

他们必须引用Teams表和名为TeamNames的列。

但是,我不知道如何让这个选择语句正常工作。

SELECT
   Tournaments.TourneyDate, 
   Tournaments.TourneyLocation, 
   Teams.TeamName, 
   Teams.TeamName
FROM
   Tournaments
INNER JOIN Tourney_Matches ON (Tournaments.TourneyID=Tourney_Matches.TourneyID)
INNER JOIN Teams ON (Tourney_Matches.OddLaneTeamID=Teams.TeamID 
                     OR Tourney_Matches.EvenLaneTeamID=Teams.TeamID);

我尝试使用此语句,但它在两个id列中显示相同的名称。

这是它的基础。

https://i.stack.imgur.com/mIQX7.png

问题是 - 显示锦标赛日期,锦标赛位置,奇数车道队名,甚至车道队名 对于锦标赛中的每场比赛

必须在子查询中完成。

1 个答案:

答案 0 :(得分:0)

修改

如果必须在子查询中完成,则:

SELECT
   Tournaments.TourneyDate, 
   Tournaments.TourneyLocation, 
   (SELECT TeamName FROM Teams WHERE TeamID = Tourney_Matches.OddLaneTeamID) AS 'Odd Lane Team', 
   (SELECT TeamName FROM Teams WHERE TeamID = Tourney_Matches.EvenLaneTeamID) AS 'Even Lane Team' 
FROM
   Tournaments
   INNER JOIN Tourney_Matches ON (Tournaments.TourneyID=Tourney_Matches.TourneyID)

OLD ANSWER

试试这个(Source of insipration):

SELECT
   Tournaments.TourneyDate, 
   Tournaments.TourneyLocation, 
   OddLaneTeams.TeamName, 
   EvenLaneTeams.TeamName 
FROM
   Tournaments
INNER JOIN Tourney_Matches ON (Tournaments.TourneyID=Tourney_Matches.TourneyID)
INNER JOIN Teams AS OddLaneTeams ON Tourney_Matches.OddLaneTeamID = OddLaneTeams.TeamID
INNER JOIN Teams AS AwayLaneTeams ON Tourney_Matches.EvenLaneTeamID = EvenLaneTeams.TeamID