InnoDB监控输出不清晰,外键约束失效

InnoDB monitor output unclear, foreign key constraint fails

我有两个数据库 table,InnoDB,都有一个列 id_fornitore,无法创建外键,我不明白为什么。这是一个简单的外键,我已经在同一个 table 上成功创建了其他外键。 这是我的查询:

ALTER TABLE tbl_prima_nota
ADD CONSTRAINT fk_id_fornitore
FOREIGN KEY (id_fornitore) REFERENCES tbl_fornitori(id_fornitore)
ON DELETE SET NULL
ON UPDATE CASCADE

这里是数据库状态监视器的输出:

Foreign key constraint fails for table `fatturazione2`.`#sql-68_409`:
,
 CONSTRAINT `fk_id_fornitore` FOREIGN KEY (`id_fornitore`) REFERENCES `tbl_fornitori` (`id_fornitore`) ON DELETE SET NULL ON UPDATE CASCADE
Trying to add in child table, in index fk_id_fornitore tuple:
DATA TUPLE: 2 fields;
0: len 4; hex 80000000; asc     ;;
1: len 4; hex 80000001; asc     ;;

But in parent table `fatturazione2`.`tbl_fornitori`, in index  uk_id_fornitore,
the closest match we can find is record:
PHYSICAL RECORD: n_fields 2; compact format; info bits 0
0: len 4; hex 80000001; asc     ;;
1: len 4; hex 80000001; asc     ;;

有人能理解这是怎么回事吗?非常感谢。

更新 感谢 Bill Karwin for the query, and Rick James 为我指明了正确的方向。问题是:当我第一次将列 id_fornitore 添加到 table tbl_prima_nota 时,我允许 NULL 作为可能的值,但我没有选择它作为 Default;在创建列时,由于 table 已经填充,MySQL 在每行中添加了 0 作为默认值,但 0 不同于 NULL。作为一个快速的解决方案,由于 id_fornitore 列是空的,我将其从 tbl_prima_nota 中删除,然后使用 NULL 作为默认值重新创建,然后我可以毫无问题地创建外键。

子 table 的外键中的每个值都必须引用父 table 的主键或唯一键中的相应值。

您不能在列 tbl_prima_nota.id_fornitore 上创建外键,因为该列包含引用的 tbl_fornitori.id_fornitore.

中缺少的一些值

您可以查询在父 table 中缺少外键值的子 table 中的行:

SELECT pn.*
FROM tbl_prima_nota AS pn
LEFT OUTER JOIN tbl_fornitori AS f USING (id_fornitore)
WHERE f.id_fornitore IS NULL;

您必须将缺少值的行添加到 tbl_fornitori,或者从 tbl_prima_nota 中删除这些行,或者更新这些行以更改外键列中的值。