Get current rank using mysql

点点圈 提交于 2020-01-25 01:58:08

问题


i've got this query to get the rank of rows, order by some field

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, id, ammopacks
  FROM users
  GROUP BY id
  ORDER BY ammopacks DESC;

How about getting the rank of "x" id, without ranking all them before? I don't want to know all users rank, just only one id.

Is it possible?

Thanks in advance


回答1:


You can do this with a subquery:

select count(*) as rank
from users u
where u.ammopacks >= (select ammopacks from users u2 where u2.id = x)

This doesn't do exactly the same thing. This will do a real ranking, where users with the same value of ammopacks will have the same rank. The original would give different users different sequential values in this case.

To get this effect, you can do:

select count(*) as rank
from users u
where u.ammopacks > (select ammopacks from users u2 where u2.id = x) or
      (u.ammopacks = (select ammopacks from users u2 where u2.id = x) and
       u.id <= x
      )


来源:https://stackoverflow.com/questions/16451670/get-current-rank-using-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!