2016-11-25 30 views
1

我有一個表格和一個查詢,我用它來返回一個進球數最多的球員列表。是否可以向此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   | 
+----------------+------------+ 

是否可以修改上述查詢並添加joinusers表:

+--------+-----------+ 
| id  | user_name | 
+---------------------+ 
| 2  | John  | 
| 7  | Andrew  | 
| 14  | Charles | 
+--------+------------+ 

要得到的輸出:

+----------------+----------------+------------+ 
|user_name  | Player   | sum(goals) | 
+----------------+----------------+------------+ 
| John   | 2    | 94   | 
| Charles  | 14    | 63   | 
| Andrew   | 7    | 43   | 
+----------------+----------------+------------+ 
+0

遊戲中是否只有2名玩家?不應該每個玩家都有一個玩家表嗎? –

回答

0

簡短的回答 - 是的,你可以:

select u.user_name, 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 
join users u on p.player = u.id 
group by player 
order by sum(goals) desc 
+1

優秀!!有效!這就是我喜歡一個很長的問題的簡短答案! :) – Northfield82

1

您可以用join做到這一點。您也可以表達如下:

select u.*, 
     (select sum(case when u.id = r.player1_id then r.player1_goals else r.player2_goals) 
     from results r 
     where r.community_id = 5 and 
       u.id in (r.player1_id, r.player2_id) 
     ) as goals 
from users u;