Can table columns with a Foreign Key be NULL?(带有外键的表列可以为 NULL 吗?)
问题描述
我有一个表,其中包含多个指向其他表的 ID 列.
I have a table which has several ID columns to other tables.
我想要一个外键仅在我将数据放入时强制完整性.如果我稍后进行更新以填充该列,那么它也应该检查约束.
I want a foreign key to force integrity only if I put data in there. If I do an update at a later time to populate that column, then it should also check the constraint.
(这可能取决于数据库服务器,我使用的是 MySQL 和 InnoDB 表类型)
(This is likely database server dependant, I'm using MySQL & InnoDB table type)
我相信这是一个合理的期望,但如果我错了,请纠正我.
I believe this is a reasonable expectation, but correct me if I am wrong.
推荐答案
是的,您只能在值不为 NULL 时强制执行约束.这可以通过以下示例轻松测试:
Yes, you can enforce the constraint only when the value is not NULL. This can be easily tested with the following example:
CREATE DATABASE t;
USE t;
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT NULL,
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=INNODB;
INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)
INSERT INTO child (id, parent_id) VALUES (2, 1);
-- ERROR 1452 (23000): Cannot add or update a child row: a foreign key
-- constraint fails (`t/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY
-- (`parent_id`) REFERENCES `parent` (`id`))
第一次插入会通过,因为我们在 parent_id
中插入了一个 NULL.由于外键约束,第二次插入失败,因为我们试图插入 parent
表中不存在的值.
The first insert will pass because we insert a NULL in the parent_id
. The second insert fails because of the foreign key constraint, since we tried to insert a value that does not exist in the parent
table.
这篇关于带有外键的表列可以为 NULL 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有外键的表列可以为 NULL 吗?


基础教程推荐
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01