从同一 Table 加入同一列两次

Join Same Column from Same Table Twice

我是 SQL 世界的新手。我想用 Teams.name 列中的相应条目替换 Games.home_team_idGames.away_team_id

首先,我首先初始化一小部分 table 数据:

    CREATE TABLE Games (id,away_team_id INT,away_team_score INT,home_team_id INT, home_team_score INT);
    CREATE TABLE
    INSERT INTO Games (id,away_team_id,away_team_score,home_team_id,home_team_score)
    VALUES
    (1,1,1,2,4),
    (2,1,3,3,2),
    (3,1,1,4,1),
    (4,2,0,3,2),
    (5,2,3,4,1),
    (6,3,5,4,2)
    ;
    INSERT 0 6

然后我创建一个参考模板table

    CREATE TABLE Teams (id INT, name VARCHAR(63);
    CREATE TABLE
    INSERT INTO Teams (id, name)
    VALUES
    (1, 'Oogabooga FC'),
    (2, 'FC Milawnchair'),
    (3, 'Ron\'s Footy United'),
    (4, 'Pylon City FC')
    ;
    INSERT 0 4

我希望 table 显示为:

    | id | away_team_name | away_team_score | home_team_name | home_team_score |
    -----+----------------+-----------------+----------------+------------------
    | 1  | Oogabooga FC   | 1               | FC Milawnchair | 4               |
     ...

我设法获得一个连接查询,以使用此 JOIN:

away_team_name 字段中显示来自 Teams.name 的第一个值
    SELECT
      Games.id,
      Teams.name AS away_team_name,
      Games.away_team_score,
      Teams.name AS home_team_name,
      Games.home_team_score
    FROM Games
      JOIN Teams ON Teams.id = Games.away_team_id
    ;
    | id | away_team_name | away_team_score | home_team_name | home_team_score |
    -----+----------------+-----------------+----------------+------------------
    | 1  | Oogabooga FC   | 1               | Oogabooga FC   | 4               |
    ...

但是现在当我调用它两次时我卡住了 JOIN 它显示错误:

     SELECT
       Games.id,
       Teams.name AS away_team_name,
       Games.away_team_score,
       Teams.name AS home_team_name,
       Games.home_team_score
     FROM Games
       JOIN Teams ON Teams.id = Games.away_team_id
       JOIN Teams ON Teams.id = Games.home_team_id
     ;
    ERROR:  table name "teams" specified more than once

你如何引用相同的引用同一列的相同 table 两次以进行连接?

您需要为 table 的至少一个实例指定一个别名;最好两者都有。

 SELECT
   Games.id,
   Away.name AS away_team_name,
   Games.away_team_score,
   Home.name AS home_team_name,
   Games.home_team_score
 FROM Games
   JOIN Teams AS Away ON Away.id = Games.away_team_id
   JOIN Teams AS Home ON Home.id = Games.home_team_id

解释:当您两次加入同一个 table 时,DBMS(在您的例子中是 PostgreSQL)无法识别您在使用时引用的 table 中的哪一个它的领域;解决此问题的方法是为连接的 table 分配别名,就像为列分配别名一样。通过这种方式,您可以指定在 SELECTJOINWHERE 语句中引用的已连接实例。