这是一个带有两个外键的表的演示,我违反了其中一个。但是哪一个?
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 STATUSG(G 是为了避免在结果周围出现一个巨大的框)。输出有点长,但其中一部分会显示最近外键错误的详细信息:
...
------------------------
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