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

前端 未结 21 2713
生来不讨喜
生来不讨喜 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条回答
  •  旧时难觅i
    2020-11-22 02:10

    I had this exact same problem about three different times. In each instance it was because one (or more) of my records did not conform to the new foreign key. You may want to update your existing records to follow the syntax constraints of the foreign key before trying to add the key itself. The following example should generally isolate the problem records:

    SELECT * FROM (tablename)
        WHERE (candidate key) <> (proposed foreign key value) 
            AND (candidate key) <> (next proposed foreign key value)
    

    repeat AND (candidate key) <> (next proposed foreign key value) within your query for each value in the foreign key.

    If you have a ton of records this can be difficult, but if your table is reasonably small it shouldn't take too long. I'm not super amazing in SQL syntax, but this has always isolated the issue for me.

提交回复
热议问题