我有两个数据库表,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 ;;
有人能理解这里发生了什么吗?非常感谢。
更新感谢比尔·卡尔温的询问,里克·詹姆斯给我指出了正确的方向。问题是:当我第一次添加列 id_fornitore
到table上去 tbl_prima_nota
我答应了 NULL
作为一个可能的值,但我没有选择它作为 Default
; 在创建列时,由于表已经填充,mysql添加了 0
作为每行的默认值,但是 0
不同于 NULL
. 作为一个快速的解决办法,把柱子塞住 id_fornitore
是空的,我把它从 tbl_prima_nota
我用 NULL
作为默认值,然后我可以毫无问题地创建外键。
1条答案
按热度按时间yxyvkwin1#
子表外键中的每个值都必须引用父表主键或唯一键中的相应值。
不能在列上创建外键
tbl_prima_nota.id_fornitore
因为该列包含引用的tbl_fornitori.id_fornitore
.可以查询父表中缺少外键值的子表中的行:
必须将行添加到
tbl_fornitori
或者从中删除行tbl_prima_nota
,或更新这些行以更改外键列中的值。