php - 在此分数表中查找我以前的排名的查询是什么?

标签 php mysql sql

我目前正在使用此查询来查找玩家的排名:

select
    coalesce(
        (
            select count(1)
            from scores b
            where
                b.top > a.top OR
                (
                    b.top = a.top AND
                    b.time < a.time
                )
        ), 0
    ) + 1 Rank
from
    Scores a
where
    user = ?

我有一个这样的分数表:

id           int
user         varchar(100)
time         int (timestamp)
top          int

最近的表格是这样的:

id           int
user         varchar(100)
time         int (timestamp)
score        int
istopscore   int (boolean 1/0)

数据库已经填满了数据,所以我不能简单地改变数据库的结构。最近的表有200,000多行,所以排序需要很多时间。我正试图找到一种方法来尽快完成此操作。

我如何找到玩家之前的段位?这是我尝试过的:

select
    coalesce(
        (
            select count(1)
            from recent b
            where
                b.istopscore = 1 AND
                (
                    (
                        b.score > a.top AND
                        b.time <= a.time
                    ) OR
                    (
                        b.score = a.top AND
                        b.time < a.time
                    )
                )
            ), 0) + 1 Rank
from scores a
where user = ?

这个查询的问题在于,如果一个用户获得了多个新的最高分,它会计算所有这些,所以它不会给出正确的结果。

如有任何帮助,我们将不胜感激。

最佳答案

我认为您的查询几乎是正确的。要克服多个最高分的问题,您可以使用 count(distinct username),例如 this :

select
    coalesce(
        (
            select count(distinct username)
            from recent b
            where
                b.istopscore = 1 AND
                (
                    (
                        b.score > a.top AND
                        b.time <= a.time
                    ) OR
                    (
                        b.score = a.top AND
                        b.time < a.time
                    )
                )
            ), 0) + 1 Rank
from scores a
where username = 'Echo'

关于php - 在此分数表中查找我以前的排名的查询是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34934919/

相关文章:

php - 限制要获取的 RSS 提要数量

Javascript:如何打印 $_SESSION 数组中的值?

mysql - MaxScale JSON 缓存规则

sql - 在 Maven 测试阶段初始化数据库用于测试目的

SQLITE:显示每个类别的总计(总和)

PHP 显示最流行的标签

php - 大量数据和 PHP 错误

mysql - 重用子查询中的计算数据

mysql - 我们可以将什么条件作为 JOIN 的 ON 的一部分?

php - 如何使用 PHP 使用另一个表中的 id 获取一个表的名称