Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

前端 未结 21 2278
生来不讨喜
生来不讨喜 2020-11-22 01:32

I\'m having a bit of a strange problem. I\'m trying to add a foreign key to one table that references another, but it is failing for some reason. With my limited knowledge o

21条回答
  •  孤独总比滥情好
    2020-11-22 02:36

    I had the same problem today. I tested for four things, some of them already mentioned here:

    1. Are there any values in your child column that don't exist in the parent column (besides NULL, if the child column is nullable)

    2. Do child and parent columns have the same datatype?

    3. Is there an index on the parent column you are referencing? MySQL seems to require this for performance reasons (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html)

    4. And this one solved it for me: Do both tables have identical collation?

    I had one table in UTF-8 and the other in iso-something. That didn't work. After changing the iso-table to UTF-8 collation the constraints could be added without problems. In my case, phpMyAdmin didn't even show the child table in iso-encoding in the dropdown for creating the foreign key constraint.

提交回复
热议问题