MySQL Error 1215: Cannot add foreign key constraint

前端 未结 30 3190
予麋鹿
予麋鹿 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:15

    Error 1215 is an annoying one. Explosion Pill's answer covers the basics. You want to make sure to start from there. However, there are more, much more subtle cases to look out for:

    For example, when you try to link up PRIMARY KEYs of different tables, make sure to provide proper ON UPDATE and ON DELETE options. E.g.:

    ...
    PRIMARY KEY (`id`),
    FOREIGN KEY (`id`) REFERENCES `t` (`other_id`) ON DELETE SET NULL
    ....
    

    won't fly, because PRIMARY KEYs (such as id) can't be NULL.

    I am sure, there are even more, similarly subtle issues when adding these sort of constraints, which is why when coming across constraint errors, always make sure that the constraints and their implications make sense in your current context. Good luck with your error 1215!

提交回复
热议问题