[英]#1452 - Cannot add or update a child row: a foreign key constraint fails
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. 我的餐厅表具有
restaurant_id
列之一,它是该表的主键。
Menu table has three columns menu_id
, menu_name
and restaurant_id
. 菜单表具有三列
menu_id
, menu_name
和restaurant_id
。 Now when i run 现在当我跑步
ALTER TABLE `menu` ADD FOREIGN KEY ( `restaurant_id` ) REFERENCES `restaurants` (`restaurant_id`);
then i got error #1452. 然后我得到了错误#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. 听起来好像该列中已有的数据不满足外键要求,这意味着您要么在“菜单”表的restaurant_id中具有空值,要么在餐馆的restaurant_id中不存在该值。 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.
如果您只希望从此刻开始强制执行外键,则需要“ nocheck”,否则需要使数据满足约束的要求。 To add a nocheck foreign key, this is what you need:
要添加nocheck外键,这是您需要的:
ALTER TABLE menu with NOCHECK
ADD CONSTRAINT [FK_menu_restaurants] FOREIGN KEY ([restaurant_id])
REFERENCES restaurants([restaurant_id])
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.