MySQL Error 1215: Cannot add foreign key constraint

前端 未结 30 2817
予麋鹿
予麋鹿 2020-11-22 01:37

I am trying to forward engineer my new schema onto my db server, but I can\'t figure out why I am getting this error. I\'ve tried to search for the answer here, but everyth

相关标签:
30条回答
  • 2020-11-22 02:16

    This also happens when the type of the columns is not the same.

    e.g. if the column you are referring to is UNSIGNED INT and the column being referred is INT then you get this error.

    0 讨论(0)
  • 2020-11-22 02:18

    For me it was the column types. BigINT != INT.

    But then it still didn't work.

    So I checked the engines. Make sure Table1 = InnoDB and Table = InnoDB

    0 讨论(0)
  • 2020-11-22 02:19

    In my case I had to disable FOREIGN KEY checks as the source tables did not exist.

    SET FOREIGN_KEY_CHECKS=0;

    0 讨论(0)
  • 2020-11-22 02:19

    I had the same error once. I just simply restarted the MySQL server and fixed the problem.

    0 讨论(0)
  • 2020-11-22 02:20

    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.

    0 讨论(0)
  • 2020-11-22 02:21

    In my case, I had deleted a table using SET FOREIGN_KEY_CHECKS=0, then SET FOREIGN_KEY_CHECKS=1 after. When I went to reload the table, I got error 1215. The problem was there was another table in the database that had a foreign key to the table I had deleted and was reloading. Part of the reloading process involved changing a data type for one of the fields, which made the foreign key from the other table invalid, thus triggering error 1215. I resolved the problem by dropping and then reloading the other table with the new data type for the involved field.

    0 讨论(0)
提交回复
热议问题