InnoDB监视器输出不清楚,外键约束失败

时间:2018-10-26 17:52:01

标签: mysql foreign-keys output 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。在创建列时,由于已经填充了表,因此MySQL在每一行中将0添加为默认值,但是0NULL不同。作为一种快速解决方案,请检查列id_fornitore为空,我从tbl_prima_nota中删除了该列,并使用NULL作为默认值重新创建,然后我可以毫无问题地创建外键。 / p>

1 个答案:

答案 0 :(得分:0)

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

您无法在列'c上创建外键,因为该列包含某些在引用的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删除行,或更新这些行以更改外键列中的值。