Insert sequential number in MySQL

前端 未结 3 2032
無奈伤痛
無奈伤痛 2020-12-05 13:57

I added an empty column to a table and now I want to insert sequential numbers to its rows. Is it possible to do it using SQL?

相关标签:
3条回答
  • 2020-12-05 14:33

    Run the following queries to have incremented value in yourField column:

    SELECT @i:=0;
    UPDATE yourTable SET yourField = @i:=@i+1;
    
    0 讨论(0)
  • 2020-12-05 14:43

    As I said in comments you can update every row with it's row number,

    Here is a link to how to calculate rownum it mysql.

    To rephrase:

    update player,
           (select @rownum:=@rownum+1 ‘rank’, p.* 
            from player p,
            (SELECT @rownum:=0) r 
            order by score desc) player1
     set thatColumn= rank
     where player.id = player1.id
    
    0 讨论(0)
  • 2020-12-05 14:49

    try this auto increment if you wanted to have incremental number in your table for each insert that you do

    create table WithAutoInc(somID int AUTO_INCREMENT,somName_ char(100) ,primary key(somID ));
    

    now to insert you can do this

     insert into WithAutoInc (somName_) values ('presley');
    

    the result is

    enter image description here

    0 讨论(0)
提交回复
热议问题