我有一個表格和一個查詢,我用它來返回一個進球數最多的球員列表。是否可以向此SQL語句添加JOIN?
該查詢效果很好,但爲了讓我獲得用戶名,我將不得不根據返回的結果(player_id)執行另一個查詢。
是否有可能修改我現有的查詢加入兩個表?我知道這是可能的普通查詢,我只是不確定是否在這個實例中,因爲返回的自定義結果表。
這是我最初的表,稱爲results
:
+----------------+-------------+-----+
| Field | Type | Key |
+----------------+-------------+-----+
| results_id | int | Pri |
| community_id | int | |
| player1_id | int | |
| player1_goals | int | |
| player2_id | int | |
| player2_goals | int | |
+----------------+-------------+-----+
這是我用回我的結果查詢:
select player, sum(goals) from
((select player1_id as player, player1_goals as goals from results where community_id = 5)
union all
(select player2_id as player, player2_goals as goals from results where community_id = 5)
) p
group by player
order by sum(goals) desc
這是怎麼被退回我的結果:
+----------------+------------+
| Player | sum(goals) |
+----------------+------------+
| 2 | 94 |
| 14 | 63 |
| 7 | 43 |
+----------------+------------+
是否可以修改上述查詢並添加join
我users
表:
+--------+-----------+
| id | user_name |
+---------------------+
| 2 | John |
| 7 | Andrew |
| 14 | Charles |
+--------+------------+
要得到的輸出:
+----------------+----------------+------------+
|user_name | Player | sum(goals) |
+----------------+----------------+------------+
| John | 2 | 94 |
| Charles | 14 | 63 |
| Andrew | 7 | 43 |
+----------------+----------------+------------+
遊戲中是否只有2名玩家?不應該每個玩家都有一個玩家表嗎? –