mysql - 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
,然后我可以毫无问题地创建外键。
解决方案
子表的外键中的每个值都必须引用父表的主键或唯一键中的对应值。
您无法在列上创建外键,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
,或者更新这些行以更改外键列中的值。
推荐阅读
- css - 具有响应效果的绝对位置
- mysql - 如果值存在于其他表中,则从该表中返回另一个值
- java - 调用名称在字符串中的类
- kubernetes - 推出后 kubernetes UnexpectedAdmissionError
- php - 如何根据数据库中存在的值显示星号(1 到 5)
- python - 根据不同列的值对数据框执行查找
- search - 图书馆路径德尔福里约
- python - 向后消除:“numpy.ndarray”对象没有属性“列”
- c# - 使用 SQL Server 数据库和实体框架错误的 Windows 应用程序部署
- .net - 嵌套的 Try-Catch:为外部 try catch 循环抛出异常