我有两个数据库表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
添加为默认值,但是0
与NULL
不同。作为一种快速解决方案,请检查列id_fornitore
为空,我从tbl_prima_nota
中删除了该列,并使用NULL
作为默认值重新创建,然后我可以毫无问题地创建外键。 / p>
答案 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
删除行,或更新这些行以更改外键列中的值。