我有以下表格:

   match

 id   |   rival_team
----------------------
|  1  |   chelsea fc
|  2  |   real madrid


   player

 ID   |   name    |   last_name  |
---------------------------------
|  1  |    John   |      Doe     |
|  2  |   Peter   |   Williams   |


   called_up_players

 match_id   |   player_id  |  substitution_id  |
---------------------------|-------------------|
|     1     |      1       |         1         |
|     1     |      2       |        NULL       |


   substitution

|     id    |   match_id   | substitute_player_id | replaced_player_id |
---------------------------|----------------------|--------------------|
|     1     |      1       |           1          |          2         |

我有以下SQL语句
SELECT called_up_players.match_id, match.rival_team, player.name,
           player.last_name, substitution.id
FROM called_up_players, substitution, player, match
WHERE called_up_players.substitution_id = substitution.substitute_player_id
         AND player.id = called_up_players.substitution_id;

以及以下输出:
match_id| rival_team |   name   | last_name | substitution_id
--------+------------+----------+-----------+-----------
      1 | chelsea fc |   John   |    Doe    |         1
      1 | real madrid|   John   |    Doe    |         1
(2 rows)

但是,我希望输出如下
match_id| rival_team |   name   | last_name | substitution_id
--------+------------+----------+-----=-----+----------------
      1 | chelsea fc |   John   |    Doe    |         1
      2 | real madrid|   John   |    Doe    |        NULL

显示所有被征召入队的比赛。无论球员是否参与了替换,我都希望有名称和替换id的列
我想我可以使用连接来实现这一点,但是我不知道如何连接表,所以我可以有类似于上面的输出。我试了很多陈述,但都错了。

最佳答案

您将在没有联接条件的情况下联接以匹配,因此这将成为交叉联接而不是内部联接。
这就是为什么不同的连接语法被认为是最佳实践的一个例子:

FROM called_up_players
INNER JOIN substitution ON called_up_players.substitution_id = substitution.substitute_player_id
 INNER JOIN player ON player.id = called_up_players.substitution_id
 INNER JOIN match ON ???

关于sql - 如何在SQL中联接这些表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41070490/

10-12 17:16
查看更多