可以使用外键的表列为null吗? [英] Can table columns with a foreign key be null?

查看:479
本文介绍了可以使用外键的表列为null吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个表,其中有几个ID列到其他表。我想要一个外键强制完整性,如果我把数据放在那里。如果我稍后做一个更新填充该列,那么它仍然会检查约束(这可能是数据库服务器依赖,我使用MySQL和InnoDB表类型)。

For example, I have a table which has several ID columns to other tables. I want a foreign key to force integrity only if I do put data in there. If I do an update at a later time to populate that column then it will still check the constraint (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 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`))

insert将会传递,因为我们在 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天全站免登陆