根据列在结果中的位置更新列

时间:2015-11-25 23:10:28

标签: mysql sql

我有一个循环查看每个结果并更新列的查询:

SET @counter = 0;
UPDATE users SET rank_level = @counter := @counter + 1 ORDER BY level DESC;
SELECT rank_level, level FROM users ORDER BY rank_level ASC;

哪个输出:

enter image description here

但我想要做的只是在级别值改变时增加变量。因此,如果两行具有相同的级别,则它们的排名也相同。

有什么想法吗?感谢。

2 个答案:

答案 0 :(得分:0)

rank()在MySQL中有点棘手。一种方法是使用相关子查询:

select u.*,
       (select count(*) + 1
        from users u2
        where u2.level < u.level
       ) as rank
from users u;

放入update这很棘手。假设您有userId列,则可以使用join

update users u join
       (select u.*,
               (select count(*) + 1
                from users u2
                where u2.level < u.level
               ) as rank
        from users u
       ) ur
       on u.userId = ur.userId
    set rank_level = rank;

使用变量进行排名相当棘手(row_number()dense_rank()更容易),因为它需要三个变量。这是select版本:

select u.*,
       (@r := if(@l = level,
                 if(@rn := @rn + 1, @r, @r)
                 if(@l := level,
                    @rn := @rn + 1, @rn := @rn + 1
                   )
                )
       ) as ranking
from users u cross join
     (select @l := -1, @rn : = 0, @r := 0) params
order by level;

答案 1 :(得分:0)

所以最后我接受了这个:

SET @prev_value = NULL;
SET @rank_count = 0;

UPDATE users SET rank_level = CASE
  WHEN @prev_value = level THEN @rank_count
  WHEN @prev_value := level THEN @rank_count := @rank_count + 1
END
ORDER BY level DESC;

基于这个答案:Rank function in MySQL