mySQL“高分榜” - 查询

时间:2010-01-22 15:59:53

标签: php mysql

你好世界各地的编码员,

我正在开展一个项目,用户可以做某些事情并获得积分。为了简化这个问题,假设我们有2个表用户

-- table user       -- table points
+---------------+    +-----------------------------+
|  id  |  name  |    |  id  |  points  |  user_id  |
+---------------+    +-----------------------------+
|  1     Tim    |    |  1      5          1        |
|  2     Tom    |    |  2      10         1        |
|  3     Marc   |    |  3      5          1        |
|  4     Tina   |    |  4      12         2        |
|  5     Lutz   |    |  5      2          2        |
+---------------+    |  6      7          1        |
                     |  7      40         3        |
                     |  8      100        1        |
                     +-----------------------------+

现在要获得完整的高分榜,我使用以下查询

SELECT u.*, SUM( p.points ) AS sum_points
FROM user u
LEFT JOIN points p ON p.user_id = u.id
GROUP BY u.id
ORDER BY sum_points DESC

为所有用户提供从头到尾的精细高分列表

+------------------------------+
|  id  |  name  |  sum_points  |
+------------------------------+
|  1     Tim       127         |
|  3     Marc      40          |
|  2     Tom       14          |
|  4     Tina      0           |
|  5     Lutz      0           |
+------------------------------+

好的回到问题本身。在单个用户的个人资料中,我想在高分榜中显示他的排名。

这可以使用单个查询来完成,例如 Tom(id = 2)排名第3位吗?

非常感谢: - )

2 个答案:

答案 0 :(得分:4)

这个想法是问“有多少玩家排在@this_user之上”:

select count(*) + 1 from 
(
    /* list of all users */
    SELECT SUM( p.points ) AS sum_points
    FROM user u
    LEFT JOIN points p ON p.user_id = u.id
    GROUP BY u.id        
) x
/* just count the ones with higher sum_points */
where sum_points > (select sum(points) from points where user_id = @this_user)

已编辑以使结果从1开始而不是从0开始

答案 1 :(得分:1)

SELECT  q.*,
        @r := @r + 1 AS rank
FROM    (
        SELECT  @r := 0
        ) vars,
        (
        SELECT  u.*,
                SUM(p.points) AS sum_points
        FROM
                user u
        LEFT JOIN
                points p
        ON      p.user_id = u.id
        GROUP BY
                u.id
        ORDER BY
                sum_points DESC
        ) q