Chris
Chris

Reputation: 59491

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 ints3_keys.

Here is a screenshot to show my 2 tables: https://i.sstatic.net/TsSDL.png

What am I missing here? Thanks.

EDIT: I should add that both tables are running InnoDB

Upvotes: 0

Views: 46

Answers (1)

Sablefoste
Sablefoste

Reputation: 4182

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. You should be able to cut and paste all of the above code in an SQL line all at once.

Upvotes: 1

Related Questions