I have two already-existing tables which look (in part) roughly like this:
CREATE TABLE parent (
old_pk CHAR(8) NOT NULL PRIMARY KEY
) ENGINE=InnoDB;
CREATE TABLE child (
parent_key CHAR(8),
FOREIGN KEY (parent_key) REFERENCES parent(old_pk)
ON UPDATE CASCADE ON DELETE CASCADE
) ENGINE=InnoDB;
I want to add a new auto-incrementing integer id
column to parent
and use it as the primary key instead, while still keeping old_pk
as a unique key and allowing other tables like child
to reference it in foreign key contraints. Unfortunately, simply saying ALTER TABLE parent DROP PRIMARY KEY
doesn't work:
Error Code : 1025
Error on rename of './data/#sql-4013_70f5e' to './data/parent' (errno: 150)
Some googling suggests that this is due to the existing foreign key reference from child
. In essence, I need a way to tell MySQL "use this other column as the primary key, but don't forget the unique-key-ness of the original one". Is there any way to accomplish this, other than just dropping the key constraints from child
and reinstating them afterwards?
Assume that I must alter the tables in place, rather than creating copies with the same data and swapping them in later. I've tried using SET FOREIGN_KEY_CHECKS = 0
before altering the table, but it does not seem to help.