MySQL - auto decrementing value

后端 未结 5 1732
孤城傲影
孤城傲影 2021-01-06 04:47

Let\'s say that I\'ve got a table, like that (id is auto-increment):

id | col1 | col2
1  | \'msg\'| \'msg\'
2  | \'lol\'| \'lol2\'
3  | \'xxx\'| \'x\'
         


        
5条回答
  •  春和景丽
    2021-01-06 05:09

    It is not good practice to change the value of an auto_increment column. However, if you are sure you want to, the following should help.

    If you are only deleting a single record at a time, you could use a transaction:

    START TRANSACTION;
    DELETE FROM table1 WHERE id = 2;
    UPDATE table1 SET id = id - 1 WHERE id > 2;
    COMMIT;
    

    However if you delete multiple records, you will have to drop the column and re-add it. It is probably not guaranteed to put the rows in the same order as previously.

    ALTER TABLE table1 DROP id;
    ALTER TABLE table1 ADD id INTEGER NOT NULL AUTO_INCREMENT;
    

    Also, if you have data that relies on these IDs, you will need to make sure it is updated.

提交回复
热议问题