Skip to content
Advertisement

Why is my mySQL throwing “ERROR 1215 (HY000): Cannot add foreign key constraint”

Error Recieved:

ERROR 1215 (HY000): Cannot add foreign key constraint

Code:

The error is being thrown on “CREATE TABLE welcomeMessage”. I tried separating the create from the foreign key using:

However it just creates the table then throws the error on the “Alter” line instead. Any help is appreciated.

Advertisement

Answer

The problem is the charset and the collation. For the foreign key to be well-formed, both the parent and the child columns must have the same charset and collation. The first statement relies on the default settings, while the second has explicit settings. If those are different from the defaults, a failure occurs.

Your code works if I just comment out the charset .... collate ... part of the second create table statement, as you can see in this db fiddle.

Both storage engines also need to be aligned. If your database uses MyISAM as a default engine, the code won’t work either (as the second statement explicitly uses InnoDB).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement