繁体   English   中英

在这个得分表中找到我以前的排名会有什么好的查询?

[英]What would be a good query to find my previous rank in this score table?

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

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) ,如下所示

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM