I have a built database with all tables set using INNODB and Foreign Keys. Now I need to modify a single table and add a new column which references another table. My query is:
ALTER TABLE test ADD newcol INT NOT NULL;
ALTER TABLE test ADD CONSTRAINT fk_test
FOREIGN KEY (newcol)
REFERENCES othertable(id);
I get the following error:
"#1452 - Cannot add or update a child row: a foreign key constraint fails."
All the other tables contain data, but I know that if I drop the test table and create it with foreign key it will work. If I drop test table it will delete a lot of records and I want to avoid copying data and re-inserting it.
Can anyone show me how to add a new column via a foreign key?
That error message means you have values in
newcolthat do not exist inothertable idcolumn. By adding a column ofINT NOT NULL, you set all the initial values for that column to0. If you do not have an id of0inothertable, you have a key mismatchTry this query:
if you get any results returned, then you have key values in
newcolthat violate the FK restraints