Home >Database >Mysql Tutorial >Why Am I Getting MySQL Error 1215: \'Cannot add foreign key constraint\'?
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:
<code class="sql">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) );</code>
The above is the detailed content of Why Am I Getting MySQL Error 1215: \'Cannot add foreign key constraint\'?. For more information, please follow other related articles on the PHP Chinese website!