Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql sort field increment value

Say I have a table

name             rank
-----------------------
John             1
Tit              3
Bernard          4

Rank 2 is missing, could have been deleted or whatever. I need a query to increment the rank field. So John would be number 1, but Tit would now be number 2, and Bernard 3.

There could be anywhere up to 100 ranks, and several missing. As long as the smallest rank is reset to number 1, and all that follow increment, it should be good.

Any ideas?

A query to update the rank field.

like image 478
user1022585 Avatar asked Jul 06 '12 10:07

user1022585


1 Answers

This will update the rank field so that it increments without holes:

SET @i := 0;
UPDATE tbl SET rank = @i:=@i+1 ORDER BY rank;
like image 200
Arnaud Le Blanc Avatar answered Sep 25 '22 10:09

Arnaud Le Blanc