首页 > 解决方案 > 排名排行榜 - MySQL

问题描述

我有一张这样的桌子

+-----+-------+
| pid | score | 
+-----+-------+      
|   1 |    120|          
|   2 |    130|    
|   3 |    100|    
|   1 |    120|        
|   2 |    130|    
|   3 |    100|      
+-----+-------+

我试图让我的用户排名。目前我正在使用这个查询,

SELECT pid
     , SUM(score) AS total_score
  FROM score 
 GROUP 
    BY pid 
 ORDER 
    BY total_score DESC

我通过这个查询得到一个按分数排序的列表,但没有得到他们的位置。我想要这样的东西

+-----+-------+------+
| pid | score | rank |
+-----+-------+------+       
|   2 |    260|    1 |       
|   1 |    240|    2 |
|   3 |    200|    3 |       
+-----+-------+------+

我可以为特定用户获得这个职位吗?喜欢

+-----+-------+------+
| pid | score | rank |
+-----+-------+------+       
|   1 |    240|    2 |        
+-----+-------+------+

我正在使用 MySQL 5.7.21。你能帮忙吗?

标签: mysqlsqldatabase

解决方案


如果你有机会使用 Mysql 8.0.2 或更高版本,你就有了函数排名。

否则您可以使用变量来设置排名:

SELECT pid,
       total_score,
       @curRank := @curRank + 1 AS rank
FROM
    (SELECT pid,
            sum(score) AS total_score
     FROM score
     GROUP BY pid
     ORDER BY total_score DESC) datas, (SELECT @curRank := 0) r

您可以过滤后仅获得所需 pid 的结果


推荐阅读