make an ID in a mysql table auto_increment (after the fact)

前端 未结 7 1510
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 20:09

I acquired a database from another developer. He didn\'t use auto_incrementers on any tables. They all have primary key ID\'s, but he did all the incrementing manually, in

7条回答
  •  余生分开走
    2020-11-30 20:36

    ALTER TABLE `foo` MODIFY COLUMN `bar_id` INT NOT NULL AUTO_INCREMENT;
    

    or

    ALTER TABLE `foo` CHANGE `bar_id` `bar_id` INT UNSIGNED NOT NULL AUTO_INCREMENT;
    

    But none of these will work if your bar_id is a foreign key in another table: you'll be getting

    an error 1068: Multiple primary key defined
    

    To solve this, temporary disable foreign key constraint checks by

    set foreign_key_checks = 0;
    

    and after running the statements above, enable them back again.

    set foreign_key_checks = 1;
    

提交回复
热议问题