简体   繁体   English

无法添加外键

[英]Cannot add Foreign Key

I'm trying to add a constraint to my table but it doesn't work. 我正在尝试向表中添加一个约束,但是它不起作用。 I'm getting: 我越来越:

#1452 - Cannot add or update a child row: a foreign key constraint fails

I've had this problem before where there was an attribute mismatch between the parent-child columns, but this time the error seems to be something else, and I cannot figure out why. 在父子列之间的属性不匹配之前,我曾遇到过此问题,但是这次错误似乎是其他原因,我无法弄清原因。

The code I'm trying is: 我正在尝试的代码是:

ALTER TABLE ts3_keys
ADD CONSTRAINT `FK_user_id` FOREIGN KEY (`member_id`) REFERENCES `ts3_users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

id is the Primary Key of the ts3_users table which I want to be the foreign key of member_id in ts3_keys . idts3_users表的主键,我想成为ts3_keysmember_id的外键。

Here is a screenshot to show my 2 tables: http://i.imgur.com/Z0CjsKw.png 这是显示我的2张桌子的屏幕截图: http : //i.imgur.com/Z0CjsKw.png

What am I missing here? 我在这里想念什么? Thanks. 谢谢。

EDIT: I should add that both tables are running InnoDB 编辑:我应该添加两个表都在运行InnoDB

Since your tables don't have any data in them, you should not be worried about the data being corrupted. 由于表中没有任何数据,因此您不必担心数据被破坏。 Please run with the following: 请运行以下命令:

SET FOREIGN_KEY_CHECKS = 0; 
ALTER TABLE ts3_keys
ADD CONSTRAINT `FK_user_id` FOREIGN KEY (`member_id`) REFERENCES `ts3_users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
SET FOREIGN_KEY_CHECKS = 1;

From your screen shots, it looks like you are running in PHPMYADMIN. 从屏幕截图中可以看出,您似乎正在PHPMYADMIN中运行。 You should be able to cut and paste all of the above code in an SQL line all at once. 您应该能够一次将所有以上代码剪切并粘贴到SQL行中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM