douxun4924 2015-05-01 23:29
浏览 89
已采纳

如何从mysql db获得一个用户的排名?

I have like this table at my mysql db for highscore.

enter image description here

and I got SQL for get rank of all users.

SELECT b.id
 , b.name
 , @rank_cnt := IF(@prev_score = b.score,@rank_cnt,@rank_cnt+1) AS rank
 , @prev_score := b.score AS score
    FROM BBR b
       CROSS
        JOIN ( SELECT @rank_cnt := 0, @prev_score := NULL) i
       ORDER BY b.score DESC, b.id DESC

if I run above SQL, I get following result,

enter image description here

But I want to know from here, specific user's rank info only.

If I wrote WHERE name = 'sim' before ORDER BY, his rank become 1. I expect here '4' as result.

How should I revise?

Thanks much.

  • 写回答

2条回答 默认 最新

  • dongqu2863 2015-05-01 23:45
    关注
    SET @rank_cnt := 0;
    SET @prev_score := NULL;
    SELECT * FROM (
       SELECT b.id
        , b.name
        , @rank_cnt := IF(@prev_score = b.score,@rank_cnt,@rank_cnt+1) AS rank
        , @prev_score := b.score AS score
       FROM BBR b
       ORDER BY b.score DESC, b.id DESC
    ) AS subQ
    WHERE subQ.name = "sim";
    

    If you are using the same connection, you shouldn't need that bogus "JOIN" to initialize your session variables.

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

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程