Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何根据排名计算用户排名_Mysql - Fatal编程技术网

Mysql 如何根据排名计算用户排名

Mysql 如何根据排名计算用户排名,mysql,Mysql,我有一个用户表,其中包含每个用户的总数,我需要计算每个用户的排名并存储它 用户表 预期结果 目前,我可以通过总排名来了解排名,但我无法计算每个排名 SELECT * from users ORDER BY total DESC 如果您只想显示基于总计列的排名,以下查询将起作用: select users.*, @rank := @rank + 1 as Rank from users cross join (select @rank := 0) r

我有一个用户表,其中包含每个用户的总数,我需要计算每个用户的排名并存储它

用户表

预期结果

目前,我可以通过总排名来了解排名,但我无法计算每个排名

SELECT * from users ORDER BY total DESC 

如果您只想显示基于总计列的排名,以下查询将起作用:

select users.*,
          @rank := @rank + 1 as Rank
    from users
    cross join (select @rank := 0) r
    order by total desc;
另一种类似的方法:

现在,如果表中已有以0初始化的秩列,则可以使用实际秩对其进行更新,如下所示:

update users
    set rank = (@rank := coalesce(@rank, 0) + 1)
    order by total desc;

希望有帮助

如果您只想显示基于总计列的排名,以下查询将起作用:

select users.*,
          @rank := @rank + 1 as Rank
    from users
    cross join (select @rank := 0) r
    order by total desc;
另一种类似的方法:

现在,如果表中已有以0初始化的秩列,则可以使用实际秩对其进行更新,如下所示:

update users
    set rank = (@rank := coalesce(@rank, 0) + 1)
    order by total desc;

希望有帮助

这里是一个简单的查询,不涉及用户定义的变量

select id,name,total,
(
  select count(distinct total) 
  from users b
  where a.total < b.total
) +1 rank
from users a
注:上面的查询还注意到,如果有1个以上的用户具有相同的总数,那么它将分配相同的排名,就像用户3、5和6具有相同的总值,所以他们应该获得相同的排名

或者,如果要更新现有表,可以将更新查询编写为

update users a
join (
  select id,
  (
      select count(distinct total) 
      from users d
      where c.total < d.total
  ) +1 rank
  from users c
) b on a.id = b.id
set a.rank = b.rank

这是一个简单的查询,不涉及用户定义的变量

select id,name,total,
(
  select count(distinct total) 
  from users b
  where a.total < b.total
) +1 rank
from users a
注:上面的查询还注意到,如果有1个以上的用户具有相同的总数,那么它将分配相同的排名,就像用户3、5和6具有相同的总值,所以他们应该获得相同的排名

或者,如果要更新现有表,可以将更新查询编写为

update users a
join (
  select id,
  (
      select count(distinct total) 
      from users d
      where c.total < d.total
  ) +1 rank
  from users c
) b on a.id = b.id
set a.rank = b.rank

非常感谢您的时间,我有一个问题,我说过这会处理关系,如果用户3、5和6具有相同的值,我可以让查询检查不同的字段以使它们具有不同的排名吗?@mirvatJ是的,您可以通过更改子句<非常感谢您的时间,我有一个问题说,这需要处理关系,如果用户3、5和6具有相同的值,我可以让查询检查不同的字段以使它们具有不同的排名吗?@mirvatJ yes您可以通过将子句<改为