【问题标题】:Error 1216: Cannot add or update a child row: a foreign key constraint fails错误 1216:无法添加或更新子行:外键约束失败
【发布时间】:2022-12-10 12:47:57
【问题描述】:

我正在使用 mysql 8.0.30 版。 我有一个包含 40 多列的表,其中 20 多列有外键约束。我们经常遇到这个问题

"Error 1216: Cannot add or update a child row: a foreign key constraint fails"

我了解错误的含义以及如何找出原因并解决它。但是,有这么多外键约束,这很耗时。

有没有办法找出哪个外键约束失败了?由于业务原因,我无法更改表结构或忽略外键约束。 mysql中是否有命令或设置来获取更详细的错误信息?

【问题讨论】:

    标签: mysql foreign-keys


    【解决方案1】:

    这是一个带有两个外键的表的演示,我违反了其中一个。但是哪一个?

    mysql> create table t1 ( id int primary key);
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> create table t2 (id int primary key);
    Query OK, 0 rows affected (0.01 sec)
    
    mysql> create table t3 (id int primary key, f1 int, f2 int,
     foreign key (f1) references t1(id), 
     foreign key (f2) references t2(id));
    Query OK, 0 rows affected (0.02 sec)
    
    mysql> insert into t1 values (1);
    Query OK, 1 row affected (0.00 sec)
    
    mysql> insert into t3 values (1, 1, 2);
    ERROR 1452 (23000): Cannot add or update a child row: 
     a foreign key constraint fails 
     (`test`.`t3`, CONSTRAINT `t3_ibfk_2` FOREIGN KEY (`f2`) REFERENCES `t2` (`id`))
    

    该错误会告诉您违反了哪一个。

    如果不清楚,请在 mysql 客户端中运行 SHOW ENGINE INNODB STATUSGG 是为了避免在结果周围出现一个巨大的框)。输出有点长,但其中一部分会显示最近外键错误的详细信息:

    ...
    ------------------------
    LATEST FOREIGN KEY ERROR
    ------------------------
    2022-12-09 10:11:12 0x175a53000 Transaction:
    TRANSACTION 7521, ACTIVE 0 sec inserting
    mysql tables in use 1, locked 1
    5 lock struct(s), heap size 1128, 2 row lock(s), undo log entries 1
    MySQL thread id 21, OS thread handle 6268727296, query id 694 localhost root update
    insert into t3 values (1, 1, 2)
    Foreign key constraint fails for table `test`.`t3`:
    ,
      CONSTRAINT `t3_ibfk_2` FOREIGN KEY (`f2`) REFERENCES `t2` (`id`)
    Trying to add in child table, in index f2 tuple:
    DATA TUPLE: 2 fields;
     0: len 4; hex 80000002; asc     ;;
     1: len 4; hex 80000001; asc     ;;
    
    But in parent table `test`.`t2`, in index PRIMARY,
    the closest match we can find is record:
    PHYSICAL RECORD: n_fields 1; compact format; info bits 0
     0: len 8; hex 696e66696d756d00; asc infimum ;;
    ...
    

    注意这显示了最新的外键错误在任何会话中,因此如果错误经常发生,您必须在一个错误被下一个替换之前快速获取详细信息。另见https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html#foreign-key-errors

    【讨论】:

      猜你喜欢
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2020-10-04
      相关资源
      最近更新 更多