MySQL Error 1215: "Cannot add foreign key constraint"
When attempting to create a foreign key constraint in MySQL, it is crucial to ensure that both the referenced field and the foreign key field adhere to specific requirements. Here's how to diagnose and resolve this error:
Engine Consistency
Data Type and Length
Collation
Uniqueness
Null Handling
Additional Symptoms
If the error persists, run the command SHOW ENGINE INNODB STATUS; to reveal more specific details.
Incorrect Statement
The provided SQL statement creates a table named "course" with a foreign key constraint referencing the "department" table on the "dept_name" field. However, this statement is incorrect because it lacks the datatype specification for the "dept_name" field. To rectify this, the statement should be modified as follows:
create table course (
course_id varchar(7),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key(course_id),
foreign key (dept_name) references department(dept_name)
);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3