首页 > 解决方案 > 如何使用 max 函数重写此“组函数的无效使用”查询以查找排名

问题描述

我有一个这样的查询,给出分数和排行榜首字母:

select MAX(score) as score, leaderboard_initials
from players p, games g where p.google_id = g.google_id
group by p.google_id
order by MAX(score) DESC;

Players有一个主键google_id,它是 中的外键games

有用。

我需要显示玩家的排名,其中考虑到他们的最高得分游戏。

我在想,对于排名,我需要 1 + 该玩家之上的玩家数量。因此,该玩家的最高得分高于该玩家。因此,我尝试了以下但得到错误invalid use of group function

select 1+(SELECT count(DISTINCT p2.google_id) from players p2, games 
g2 where MAX(g2.score) > score) as rank,
MAX(score) as score, leaderboard_initials
from players p, games g where p.google_id = g.google_id
group by p.google_id
order by MAX(score) DESC;

我知道我不能MAX()在 a中使用,WHERE但我不知道如何在不这样做的情况下获得排名。有任何想法吗?

标签: mysql

解决方案


尝试这样的事情:

SELECT p.google_id, p.leaderboard_initials, bestScores.maxScore
  , COUNT(DISTINCT others.google_id) + 1 AS playerRank
FROM (
   SELECT google_id, MAX(score) AS maxScore
   FROM games
   GROUP BY google_id
) AS bestScores
INNER JOIN players AS p 
   ON bestScores.google_id = p.google_id
LEFT JOIN games AS others 
   ON bestScores.google_id <> others.google_id
   AND bestScores.maxScore < others.score
GROUP BY p.google_id, p.leaderboard_initials, bestScores.maxScore;
  • 它首先找到每个玩家的最佳分数(子查询),
  • 然后获取玩家信息(INNER JOIN 玩家),
  • 然后得到其他玩家的所有更好的分数(LEFT JOIN games as others)
  • 最后它计算得分更高的不同玩家的数量

推荐阅读