SQL JOIN与来自SQL SERVER中teams表的Team Names

时间:2019-04-17 06:35:23

标签: sql sql-server join

我想在比赛时间表中显示球队名称,我正在使用以下查询,但我同时获得了TeamA和TeamB相同的名字

SELECT m.ID AS MID,  MatchDate,  
t.Name AS TeamName, 'v' AS VS,  
t.Name AS TeamName, Group
  FROM Matches m 
JOIN Team T ON  m.TeamA_ID = t.Id 
JOIN  Team T2 ON m.TeamB_ID = t2.Id 

如何获取基于TeamA_ID,TeamB_ID的正确团队名称

桌队

ID
TeamName
TeamCountry

表匹配项

ID
MatchDate
TeamA_ID
TeamB_ID
Location
Group


ID      TeamName        TeamCountry
1       TeamOne         100
2       TeamTwo         30
3       TeamThree       80
4       TeamFour        90
5       TeamFive        98
6       TeamSix         99
7       TeamSeven       200
8       TeamEight       14


ID      MatchDate       TeamA_ID    TeamB_ID    Location    Group
1       01-01-2019      2           4           L1          A
2       02-01-2019      6           1           L1          A
3       04-01-2019      5           8           L1          B
4       06-01-2019      2           6           L1          B
5       10-01-2019      3           4           L1          C
6       16-01-2019      5           6           L1          C   

我想要结果

ID      Date            TeamName        vs      TeamName    Location    Group
1       01-01-2019      TeamTwo         v       TeamFour        L1          A
2       02-01-2019      TeamSix         v       TeamOne         L1          A
3       04-01-2019      TeamFive        v       TeamEight       L1          B
4       06-01-2019      TeamTwo         v       TeamSix         L1          B
5       10-01-2019      TeamThree       v       TeamFour        L1          C
6       16-01-2019      TeamFive        v       TeamSix         L1          C

3 个答案:

答案 0 :(得分:2)

一个简单的错误(您有两次t.Name而不是t2.Namet.Name

SELECT m.ID AS MID,  MatchDate,  
    t.Name AS TeamName,
    t2.Name AS TeamName,
    ...

答案 1 :(得分:1)

您几乎明白了。

SELECT  m.ID AS MID,  
        MatchDate,  
        T.Name AS TeamName, 
        'v' AS VS,  
        T2.Name AS TeamName, -- Should be T2.Name
        Group
FROM   Matches m 
JOIN   Team T ON  m.TeamA_ID = T.Id 
JOIN   Team T2 ON m.TeamB_ID = T2.Id 

答案 2 :(得分:1)

在选择中,您选择了两次t.Name,将第二个更改为t2.Name。

    SELECT m.ID AS MID,  MatchDate,  
t.Name AS TeamName, 'v' AS VS,  
t2.Name AS TeamName, Group
  FROM Matches m 
JOIN Team T ON  m.TeamA_ID = t.Id 
JOIN  Team T2 ON m.TeamB_ID = t2.Id