Tag Archives: 1452

MySQL failed to add foreign key error 1452

MySQL failed to add foreign keys, error 1452
For example:
Two tables user table: User class table: Grade
Each user in the user table corresponds to a class ID, namely gradeId
Namely: The primary key of the User table gradeId is the Id in the Grade table
The user table is called the primary table and the Grade table is called the slave table
[SQL]

alter table user

Add Foreign Key (gradeId) References Grade (Id);  

[error]

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

“Why”
Some gradeId in the User table do not belong to the ID in the Grade table
【 Solution 】
Modify the data so that all gradeId in the User table belong to ids in the Grade table