MySQL Error 1215: Cannot add foreign key constraint MySQL Error 1215: Cannot add foreign key constraint mysql mysql

MySQL Error 1215: Cannot add foreign key constraint


I'm guessing that Clients.Case_Number and/or Staff.Emp_ID are not exactly the same data type as Clients_has_Staff.Clients_Case_Number and Clients_has_Staff.Staff_Emp_ID.

Perhaps the columns in the parent tables are INT UNSIGNED?

They need to be exactly the same data type in both tables.


Reasons you may get a foreign key constraint error:

  1. You are not using InnoDB as the engine on all tables.
  2. You are trying to reference a nonexistent key on the target table. Make sure it is a key on the other table (it can be a primary or unique key, or just a key)
  3. The types of the columns are not the same (exception is the column on the referencing table can be nullable even if it is not nullable on the referenced table).
  4. If the PK/FK is a varchar make sure the collation is the same for both.

Update:

  1. One of the reasons may also be that the column you are using for ON DELETE SET NULL is not defined to be null. So make sure that the column is set default null.

Check these.


For others same error may not always be due to column type mismatch, you can find out more information about a mysql foriegn key error by issuing command

SHOW ENGINE INNODB STATUS;

you may find a error near the top of the printed message something like

Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint.