I am trying to add Foreign Key on table "menu" and getting Error as:
1452 - Cannot add or update a child row: a foreign key constraint fails (`#sql-c74_c5`, CONSTRAINT `#sql-c74_c5_ibfk_1` FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`restaurant_id`))
My Restaurant table has one of the columns restaurant_id
and it is Primary Key for this table.
Menu table has three columns menu_id
, menu_name
and restaurant_id
. Now when i run
ALTER TABLE `menu` ADD FOREIGN KEY ( `restaurant_id` ) REFERENCES `restaurants` (`restaurant_id`);
then i got error #1452.
Please help me out of it :)
It sounds like the data already in that column does not meet the foreign key requirements, meaning, you either have a null value in restaurant_id in the "menu" table, or you have a value that does not exist in restaurant_id in restaurants. If you want the foreign key to only be enforced from this point on, you need a "nocheck", otherwise you need to have the data meet the requirements of the constraint. To add a nocheck foreign key, this is what you need:
ALTER TABLE menu with NOCHECK
ADD CONSTRAINT [FK_menu_restaurants] FOREIGN KEY ([restaurant_id])
REFERENCES restaurants([restaurant_id])
I hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.