首页 > 解决方案 > InnoDB 监控输出不清楚,外键约束失败

问题描述

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

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的查询,以及Rick James为我指出正确的方向。问题是:当我第一次将列添加id_fornitore到表中时,tbl_prima_nota我允许NULL将其作为可能值,但我没有将其选为Default; 在列创建时,由于表已经填充,MySQL0在每一行中添加为默认值,但0不同于NULL. 作为一个快速的解决方案,因为该列id_fornitore是空的,我将其删除tbl_prima_nota并使用默认值重新创建NULL,然后我可以毫无问题地创建外键。

标签: mysqlforeign-keysoutputinnodb

解决方案


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

您无法在列上创建外键,tbl_prima_nota.id_fornitore因为该列包含引用中缺少的一些值tbl_fornitori.id_fornitore

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

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,或者更新这些行以更改外键列中的值。


推荐阅读