How to update id set from 1?

前端 未结 4 1302
清歌不尽
清歌不尽 2021-01-03 03:46

I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2

相关标签:
4条回答
  • 2021-01-03 04:14

    Of course there is a way:

    set @counter = 0;
    update table_name
    set id  = (@counter := @counter + 1);
    

    EDIT

    To avoid problem with duplicate keys you can run something like this before to temporary change current ids to negative equivalents:

    update table_name
    set id  = 0 - id;
    
    0 讨论(0)
  • 2021-01-03 04:15

    Is there any query to update my existing id and make my id start from 1 and next id 2 and so on

    What you can do is transfer the content of your table to another table. Reset the auto increment counter, insert your data back into the original table but let MySQL assign the primary key.

    Assuming your table name is mytable You do it like this:

    CREATE TABLE mytable_tmp select * from mytable;
    TRUNCATE TABLE mytable;
    ALTER TABLE mytable AUTO_INCREMENT = 1;
    INSERT INTO mytable(name) SELECT name FROM mytable_tmp ORDER BY id;
    DROP TABLE mytable_tmp;
    
    0 讨论(0)
  • 2021-01-03 04:34

    This query will work for your scenario:

    ALTER TABLE tablename DROP id
    
    ALTER TABLE tablename ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id), AUTO_INCREMENT=1
    
    0 讨论(0)
  • 2021-01-03 04:38

    In my opinion you shouldn't mess with auto_increment columns at all. Let them be as they are. Their only job is to identify a row uniquely. If you want a nice serial number use another column (make it unique if you wish)!

    You will always run into trouble and there will always happen things, that mess with your nice 1, 2, 3, ... sequence. A transaction gets rolled back? Boom, your sequence is 1, 2, 3, 5, ... instead of your intended 1, 2, 3, 4, ...

    This can also be a very heavy operation. An auto_increment column is always also a primary key. Every other index on this table includes the primary key. Every time you reset your auto_increments, every index on this table is rewritten.

    So my advice is, don't mess with auto_increments.

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