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

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

    For me, this problem was a little different and super easy to check and solve.

    You must ensure BOTH of your tables are InnoDB. If one of the tables, namely the reference table is a MyISAM, the constraint will fail.

        SHOW TABLE STATUS WHERE Name =  't1';
    
        ALTER TABLE t1 ENGINE=InnoDB;
    
    0 讨论(0)
  • 2020-11-22 02:17

    You just need to answer one question:

    Is your table already storing data? (Especially the table included foreign key.)

    If the answer is yes, then the only thing you need to do is to delete all the records, then you are free to add any foreign key to your table.

    Delete instruction: From child(which include foreign key table) to parent table.

    The reason you cannot add in foreign key after data entries is due to the table inconsistency, how are you going to deal with a new foreign key on the former data-filled the table?

    If the answer is no, then follow other instructions.

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

    Quite likely your sourcecodes_tags table contains sourcecode_id values that no longer exists in your sourcecodes table. You have to get rid of those first.

    Here's a query that can find those IDs:

    SELECT DISTINCT sourcecode_id FROM 
       sourcecodes_tags tags LEFT JOIN sourcecodes sc ON tags.sourcecode_id=sc.id 
    WHERE sc.id IS NULL;
    
    0 讨论(0)
  • 2020-11-22 02:19

    I had the same problem and found solution, placing NULL instead of NOT NULL on foreign key column. Here is a query:

    ALTER TABLE `db`.`table1`
    ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
    ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
    ADD CONSTRAINT `col_table2_fk1`
    FOREIGN KEY (`col_table2_fk`)
    REFERENCES `db`.`table2` (`table2_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION;
    

    MySQL has executed this query!

    0 讨论(0)
  • I'd the same problem, I checked rows of my tables and found there was some incompatibility with the value of fields that I wanted to define a foreign key. I corrected those value, tried again and the problem was solved.

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

    Make sure the value is in the other table otherwise you will get this error, in the assigned corresponding column.

    So if it is assigned column is assigned to a row id of another table , make sure there is a row that is in the table otherwise this error will appear.

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