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

前端 未结 21 2326
生来不讨喜
生来不讨喜 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:23

    I was readying this solutions and this example may help.

    My database have two tables (email and credit_card) with primary keys for their IDs. Another table (client) refers to this tables IDs as foreign keys. I have a reason to have the email apart from the client data.

    First I insert the row data for the referenced tables (email, credit_card) then you get the ID for each, those IDs are needed in the third table (client).

    If you don't insert first the rows in the referenced tables, MySQL wont be able to make the correspondences when you insert a new row in the third table that reference the foreign keys.

    If you first insert the referenced rows for the referenced tables, then the row that refers to foreign keys, no error occurs.

    Hope this helps.

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

    Truncate the tables and then try adding the FK Constraint.

    I know this solution is a bit awkward but it does work 100%. But I agree that this is not an ideal solution to deal with problem, but I hope it helps.

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

    It seems there is some invalid value for the column line 0 that is not a valid foreign key so MySQL cannot set a foreign key constraint for it.

    You can follow these steps:

    1. Drop the column which you have tried to set FK constraint for.

    2. Add it again and set its default value as NULL.

    3. Try to set a foreign key constraint for it again.

    0 讨论(0)
  • 2020-11-22 02:25
    UPDATE sourcecodes_tags
    SET sourcecode_id = NULL
    WHERE sourcecode_id NOT IN (
      SELECT id FROM sourcecodes);
    

    should help to get rid of those IDs. Or if null is not allowed in sourcecode_id, then remove those rows or add those missing values to the sourcecodes table.

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

    In my case, I created a new table with the same structure, created the relationships with the other tables, then extracted the data in CSV from the old table that has the problem, then imported the CSV to the new table and disabled foreign key checking and disabled import interruption, all my data are inserted to the new table that has no problem successfully, then deleted the old table.

    It worked for me.

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

    I end up delete all the data in my table, and run alter again. It works. Not the brilliant one, but it save a lot time, especially your application is still in development stage without any customer data.

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