How do I reset sequence numbers to become consecutive?

前端 未结 5 1442
清歌不尽
清歌不尽 2020-12-19 06:50

I\'ve got a mysql table where each row has its own sequence number in a \"sequence\" column. However, when a row gets deleted, it leaves a gap. So...

1
2
3
         


        
5条回答
  •  盖世英雄少女心
    2020-12-19 07:53

    This is a question that often I read here and in other forums. As already written by zerkms this is a false problem. Moreover if your table is related with other ones you'll lose relations.

    Just for learning purpose a simple way is to store your data in a temporary table, truncate the original one (this reset auto_increment) and than repopulate it.

    Silly example:

    create table seq (
    id int not null auto_increment primary key,
    col char(1)
    ) engine = myisam;
    
    insert into seq (col) values ('a'),('b'),('c'),('d');
    
    delete from seq where id = 3;
    
    create temporary table tmp select col from seq order by id;
    
    truncate seq;
    
    insert into seq (col) select * from tmp;
    

    but it's totally useless. ;)

提交回复
热议问题