具有外键的表列可以为 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.
相关文章