dras2334 2014-12-10 06:24
浏览 48
已采纳

MySQL select语句 - 如何计算当前排名

I have a table called user_rankings where votes (voted) are stored for each user. I want to display the current ranking of users (this week) that depends on how much votes the user got.

example to clarify:

  • RANK-NR, USERNAME, VOTED,
  • 1, name1, 18 times
  • 2, name1, 16 times
  • (my ranking here), myname, 13 times

In this example my ranking should be 3. If I'd have 17 votes, I would be number 2. If there would be five users above me, I would be number 8. I guess you get the point.

Now I can display the ranking number easily with an incrementing $i in PHP. But I only want to show a list limited to ten users (a top ten list) and directly after that my current ranking, if I'm not already in that top ten list. So I'm just wondering how to get my exact ranking number using MySQL. I'm assuming to have hundreds of users in this list with a different amount of votes.

This is my statement at the moment:

SELECT 
`voted`
FROM `users_ranking` 
WHERE 
`uid`='".$_SESSION['uid']."' 
AND 
WEEKOFYEAR(`date`)=WEEKOFYEAR(NOW()) 
LIMIT 1
  • 写回答

3条回答 默认 最新

  • dongwen9051 2014-12-10 07:58
    关注

    I just found out myself that this solution works:

    SELECT *
    FROM 
    (
      SELECT  @ranking:= @ranking + 1 rank,
              a.`uid`
      FROM    `users_ranking` a, (SELECT @ranking := 0) b
      ORDER BY a.`votes` DESC
    ) s
    WHERE `uid`='".$_SESSION['uid']."' 
    AND 
    WEEKOFYEAR(`date`)=WEEKOFYEAR(NOW()) 
    LIMIT 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算