MySQL give a rank to each group

2020-07-29 09:18发布

问题:

What I'm trying to do is update all rows column with the same id with increasing number and when there is no more of this id I to go on the next one.

Table:

id  column
1   0
1   0
2   0
2   0
3   0
3   0

I tried:

SELECT @i:=0;
UPDATE table SET column = @i:=@i+1

This way I updated the column but the column values goes like 1 2 3 4 5 6 and I must reset the @i back to 0 everytime when id of the row has changed. OR:

Table:

id  column
1   1
1   2
2   1
2   2
3   1
3   2

I guess this should be made by a loop. But can't get it. Plus when I tried to make a loop in the MySQL (PHPMyAdmin), it gave me an error. What I read around is that I can't make loops directly in the PHPMyAdmin or I misunderstood it?

回答1:

UPDATE table ,(SELECT @curRow := 0, @curCol := '') r SET column=
    ( CASE id WHEN @curCol  THEN @curRow := @curRow + 1  ELSE @curRow := 1 AND @curCol := id END)

Test