mysql - SQL查询获取用户排名

标签 mysql sql ranking

我正在尝试在Mysql中执行查询来获取用户的所有时间排名。 对于本月的排名,我按照以下要求设法做到了:

SELECT MAX(x.rank) AS rank
  FROM (SELECT 
               t.id_user,
               @rownum := @rownum + 1 AS rank
          FROM screengame_points t
          JOIN (SELECT @rownum := 0) r
          WHERE month = $month
      ORDER BY t.points DESC) x
 WHERE x.id_user = 4

一直以来,我都需要计算所有点的总和,所以我尝试了:

SELECT MAX(x.rank) AS rank
  FROM (SELECT 
               t.id_user,
               @rownum := @rownum + 1 AS rank
          FROM screengame_points t
          JOIN (SELECT @rownum := 0) r
    GROUP BY id_user
      ORDER BY sum(t.points) DESC) x
 WHERE x.id_user = 4

(注意“group by id_user”和“sum(t.points)”)。

但是它不起作用。我认为第二次请求的排名结果是从一个月内得分最高的到最差的。不是整个月所有积分的总和。

我该怎么做?

最佳答案

我怀疑问题在于 ORDER BY 在这两种情况下都被优化掉了。在第一种情况下,您可能只是幸运。

MySQL 文档确实表明在子查询中允许使用 ORDER BY。然而,有一个有趣的讨论here关于UNION

However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.

我强调这是关于UNION子句的;我找不到与简单子(monad)查询有关的任何内容。但是,除了最外层之外,标准 SQL 中不允许使用 ORDER BY。原因很简单。 。 。表和子查询是无序的。

您可以通过在子查询中包含LIMIT子句来欺骗MySQL。输入足够大的数字来吸引所有用户(尽管理论上这可以被优化掉)。

您还有另外两种选择来获取此信息。如果你的表不是太大,你可以使用自连接来获取排名信息。您还可以插入具有自动增量列的临时表;我认为 order by 可以在那里工作。 (而且我不考虑切换数据库,因为几乎所有其他数据库都支持 rank 函数。)

关于mysql - SQL查询获取用户排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13323867/

相关文章:

PHP/MYSQL utf8 文件打开语法错误,但通过 phpmyadmin 工作正常

php - MySQL 十进制字段在 PHP 中作为字符串返回

sql - 如何在mysql中选择某行(或在选择中给予优先权)?

mongodb - 根据 mongodb 中的积分查找用户排名

Excel创建多重条件排名

mysql - 如何构建这个关系数据库

mysql - 为什么子查询比联接更快?

mysql - 在带有列的 mysql 查询中

mysql - 仅考虑 COUNT 个特定 ID

SQL ALTER TABLE 删除级联