[英]How to join these tables in SQL
我有以下表格:
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
顯示所有被召集到John Doe名單上的比賽。 無論球員參與換人,我都希望有名稱和替換ID的列
我想我可以使用JOINS來實現這一點,但是我不知道如何聯接表,因此可以得到與上述輸出類似的東西。 我嘗試了很多聲明我出錯了。
您要加入匹配項而沒有加入條件,因此這將成為交叉聯接,而不是內部聯接。
這是為什么將不同的聯接語法視為最佳實踐的一個示例:
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 ???
多虧了Learning2Code和他的回答,我對聯接有了更多的了解,最后,我想出了一個獲得所需輸出的答案。
我不使用INNER JOIN,而是使用LEFT JOIN,以便從左側的表中檢索所有記錄,如果右側的表中沒有數據,則該字段為空
SELECT match_id, rival_team, name, last_name, substitution_id
FROM match
LEFT JOIN called_up_players ON called_up_players.match_id = match.id
LEFT JOIN player ON player.id = called_up_player.player_id
LEFT JOIN substitution ON called_up_players.substitution_id = substitution.substitution_id
WHERE player.name = 'John' AND player.last_name = 'Doe';
輸出:
partido_id | contrario | nombre | apellido | cambio_id
-------------+------------+------------+-----------+------------
1 | chelsea fc | John | Doe | 1
2 | real madrid| John | Doe |
(2 rows)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.