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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度