Reputation: 9211
I'm wondering if it's possible to add a foreign key contraint on a table that already has data. I'm have a table Suppliers and a table Ingredients
When I try to add a constraint as follows:
I'm getting the following error
MySQL said: Cannot add or update a child row: a foreign key constraint fails (`blackfisk_relations`.`#sql-223_37`, CONSTRAINT `ingredients_supplier_id_foreign` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`) ON DELETE CASCADE)
Upvotes: 2
Views: 57
Reputation: 309
If you want to add a constraint to a table with data in it, the data must satisfy the constraint (or what would be the point of adding a constraint, if the data didn't have to satisfy it?)
Your options:
(Some DBMS allow a constraint to be added with NOCHECK specified, which means the constraint will be added, but won't be applied to existing data - only new data and changes to existing data. I don't know if MySql allows this - SQL Server and Oracle do. If MySql does, you may have to script it, rather than using a GUI option.)
Upvotes: 1
Reputation: 340
If you have record against each primary key in table where you are creating foreign key then you can try to alter table.
Your error shows you have a record in table which does not exist as primary key in other table. This is preventing you from altering table.
Upvotes: 0
Reputation: 67
Of course you can, just ensure that the values of the foreign key exists on the referenced table, otherwise you will have to create all the missing values or changing their value to null
good luck
Upvotes: 1