MySQL - Cannot add or update a child row: a foreign key constraint fails

后端 未结 9 635
执念已碎
执念已碎 2021-01-07 19:25

This seems to be a common error, but for the life of me I can\'t figure this out.

I have a set of InnoDB user tables in MySQL that are tied together via foreign key;

9条回答
  •  清酒与你
    2021-01-07 19:51

    I solved my 'foreign key constraint fails' issues by adding the following code to the start of the SQL code (this was for importing values to a table)

    SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT;
    SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS;
    SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION;
    SET NAMES utf8;
    SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
    SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
    SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO';
    SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0; 
    

    Then adding this code to the end of the file

    SET SQL_MODE=@OLD_SQL_MODE;
    SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
    SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
    SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT;
    SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS;
    SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION;
    SET SQL_NOTES=@OLD_SQL_NOTES; 
    

提交回复
热议问题