How to Reset an MySQL AutoIncrement using a MAX value from another table?

前端 未结 8 668
遥遥无期
遥遥无期 2020-12-08 07:04

I know this won\'t work, tried it in various forms and failed all times. What is the simplest way to achieve the following result?

ALTER TABLE XYZ AUTO_INCRE         


        
8条回答
  •  北海茫月
    2020-12-08 07:13

    I'm creating an automated database transformation script for a new version of my application.

    In one table, I needed to change the primary auto-increment field to a different field. Since this page came up first many times while I googled a solution for it, here's a solution that eventually worked for me:

    -- Build a new ID field from entry_id, make it primary and fix the auto_increment for it:
    ALTER TABLE  `entries` ADD  `id` INT UNSIGNED NOT NULL FIRST;
    UPDATE entries SET id = entry_id;
    ALTER TABLE  `entries` ADD PRIMARY KEY (  `id` );
    
    -- ...the tricky part of it:
    select @ai := (select max(entry_id)+1 from entries);
    set @qry = concat('alter table entries auto_increment=',@ai);
    prepare stmt from @qry; execute stmt;
    
    -- ...And now it's possible to switch on the auto_increment:
    ALTER TABLE  `entries` CHANGE  `id`  `id` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT;
    

提交回复
热议问题