具有外键的表列可以为 NULL 吗? [英] Can table columns with a Foreign Key be NULL?

查看:34
本文介绍了具有外键的表列可以为 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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆