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;