douduan2272 2010-01-22 15:59
浏览 36
已采纳

mySQL“高分榜” - 查询

Hi there coders around the world,

I'm working on a project where users can do certain things and gain points for it. To simplify this question let's say we got 2 tables user and points.

-- 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        |
                     +-----------------------------+

Now to get the complete highscore-list I use the following query

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

resulting in a fine highscore-list with all users from first to last

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

Alright back to the question itself. On the profile of a single user I'd like to show his ranking within the highscore-list.

Can this be done using a single query just showing that for example Tom (id=2) is ranked in place 3?

Thanks alot :-)

  • 写回答

2条回答 默认 最新

  • dousong1926 2010-01-22 16:08
    关注

    The idea is to ask, "how many players rank above @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)
    

    Edited to make result 1-based instead of 0-based

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题