【问题标题】:How can I rewrite this 'Invalid use of group function' query using the max function to find the rank如何使用 max 函数重写此“组函数的无效使用”查询以查找排名
【发布时间】:2019-08-27 17:15:34
【问题描述】:

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

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;

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

【问题讨论】:

  • 哪个版本的 MySQL?
  • @Uueerdo 5.6.40-84.0-log

标签: mysql


【解决方案1】:

试试这样的:

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)
  • 最后计算得分更高的不同玩家的数量

【讨论】:

  • 你太棒了!我添加了order by playerRank,得到了我需要的东西。
【解决方案2】:

有几种方法。

例如,使用 SELECT 列表中的相关子查询来获取排名:

 SELECT r.score
      , r.leaderboard_initials
      , ( SELECT 1+COUNT(DISTINCT s.google_id) 
           FROM games s
          WHERE s.score > r.score
        ) AS rank_
   FROM ( SELECT MAX(g.score) AS score
               , p.leaderboard_initials
               , p.google_id
            FROM players p
            JOIN games g
              ON g.google_id = p.google_id
           GROUP
              BY p.google_id
        ) r
  ORDER
     BY r.score DESC

【讨论】:

  • 不错。我可以确认这也有效。我已经接受了 Uueerdo 的回答,因为他先到了那里。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多