如何查询此表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 |
+-------------+-----------+
答案 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;