MySQL排名系统自定义查询

MySQL ranking system custom query

我有排名系统,它是基于分数的结果。

    User | Points
    1    | 100
    2    | 197
    3    | 123
    4    | 174
    5    | 98
    ...
   197   | 21
   198   | 110
   199   | 154

假设我的user-id是197,那么首先我想知道我的rank based or points,最高分在前,最低在后,所以这里假设我的rank(user-id = 197)是# 150

获得我的排名后(如果我的排名不在前 100 名列表中)然后我想获得 100 名用户的列表,我需要获得 1 到 50 名的用户 + 125 到 175 名的用户,这样我可以也获得我在此列表中的排名,但列表排名将是结果中的实际排名

User | Points | Rank
18    | 199   | 1
22    | 198   | 2
31    | 180   | 3
19    | 174   | 4
51    | 168   | 5
+
17    | 22    | 149
197   | 21    | 150
199   | 14    | 151

我在 PHP 中有应用程序,那么获得此结果集的最佳和有效方法是什么?

返回分数及其排名的总体查询是(或者我应该说 'could be',因为它有效但可能不是最优雅的解决方案):

SET @count = 0; 
SELECT 
  user, 
  points, 
  rank 
    FROM( 
        SELECT user,
                 points, 
                    @count := @count + 1 'rank' 
         FROM scores 
         ORDER BY points DESC 
    ) as ranks;

所以如果你想知道特定用户的排名,你会在末尾添加一个 where 子句,of:

 WHERE user = 197;

关于第二部分,尤其是格式方面,我认为最好在 PHP 中完成。你可以 运行 上面的内容来获得你的 'rank',然后做这样的事情(注意:我只是在这里伪引用 PHP,而不是编写答案脚本):

$myRank = [result of above query];

if($myRank > 100) {

// retrieve first 50 results and display in query 1

echo "..."; // or in a <td>, etc.

// retrieve results x to y and display in query2, loop through a table etc.

}
else {

// retrieve the first 100 if your score is in that range

}

前 50 个结果的 SQL 将是

SET @count = 0; 
SELECT 
  user, 
  points, 
  rank 
    FROM( 
        SELECT user,
                 points, 
                    @count := @count + 1 'rank' 
         FROM scores 
         ORDER BY points DESC 
    ) as ranks
    LIMIT 0,50;

然后你必须在php中使用我们理论$myRank的输出来获得下一组结果。例如,如果您想要排名后的下一个 50,您可以将最后一行更改为:

LIMIT $myRank,$upper;

upper 的位置,在 php:

$upper = $myRank+50;

在真正确定一个完整的解决方案之前,您显然需要根据不同的场景准确确定您想要实现的目标,但希望这会有所帮助。