mysql update a column with an int based on order

前端 未结 2 632
半阙折子戏
半阙折子戏 2020-12-08 08:50

Lets say I have these columns

 uniqueID|Money|Quantity|MoneyOrder|QuantityOrder
1|23|12||
2|11|9||
3|99|100||

What I want to do is update <

相关标签:
2条回答
  • 2020-12-08 09:29

    See answers to this question:

    Updating column so that it contains the row position

    SET @counter = 0;
    
    UPDATE 
    my_table
    SET MoneyOrder = @counter := @counter + 1
    ORDER BY Money;
    
    SET @counter = 0;
    
    UPDATE 
    my_table
    SET QuantityOrder = @counter := @counter + 1
    ORDER BY Quantity;
    
    0 讨论(0)
  • 2020-12-08 09:33
    SET @rownumber = 0;    
    update mytable set Moneyorder = (@rownumber:=@rownumber+1)
    order by MoneyOrder asc
    

    or to do it in a single query you can try

    update mytable target
    join
    (
         select id, (@rownumber := @rownumber + 1) as rownum
         from mytable         
         cross join (select @rownumber := 0) r
         order by MoneyOrder asc
    ) source on target.id = source.id    
    set Moneyorder = rownum
    
    0 讨论(0)
提交回复
热议问题