如何查询此表以查找获得最多目标的玩家?

时间:2016-11-25 15:21:12

标签: mysql

如何查询此表results以找出哪个player_id在特定community_id中获得了最多的目标?

+----------------+-------------+-----+
| Field          | Type        | Key |
+----------------+-------------+-----+
| results_id     | int         | Pri |
| community_id   | int         |     |
| player1_id     | int         |     |
| player1_goals  | int         |     |
| player2_id     | int         |     |
| player2_goals  | int         |     |
+----------------+-------------+-----+

注意:玩家可以是玩家1或玩家2,因此他们的目标必须相应加起来,即:

SELECT Player ID, count (*) Goals FROM results
(SELECT SUM (player1_goals) WHERE player1_id = 2 AND community_id = 5) 
(SELECT SUM (player2_goals) WHERE player2_id = 2 AND community_id = 5) AS player_id GROUP BY Player ID ORDER BY Goals DESC

但我知道语法非常不正确......

我想要的输出是:

+-------------+-----------+
| Player ID   | Goals     |
+-------------+-----------+
| 14          | 64        |
| 8           | 43        |
| 7           | 17        |
+-------------+-----------+

1 个答案:

答案 0 :(得分:2)

您需要在组合表后汇总

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
limit 1;