本文主要是介绍外键值可为空,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文地址:http://blog.csdn.net/bisal/article/details/49706273
从感官上,外键用于限制主子表的关联关系,是一种强关联关系,那么子表的外键值不应该为空,而是都会关联到主表对应的记录上,但实际上,至少在Oracle中,外键是可以为空的,打个比方,班级是主表,学生是子表,一个班级有多名学生,一名学生肯定会关联到一个存在的班级,但来了一个转校生,还没有分班,他现在属于学生子表,但还没有关联到班级主表中的任何一条记录。
实验:
1.创建主表T_A,子表T_B,子表A_ID列作为外键关联到主表T_A的主键ID字段。
SQL> create table t_a(
id number, name varchar2(1));Table created.SQL> alter table t_a add constraint pk_t_a primary key(id);Table altered.SQL> create table t_b(id number, a_id number, name varchar2(1));Table created.SQL> alter table t_b add constraint pk_t_b primary key(id);Table altered.SQL> alter table t_b add constraint fk_b_a foreign key(a_id) references t_a(id);Table altered.
2.插入记录,其中T_B表的一条记录标明A_ID字段值为空。
SQL> insert into t_a values(1, 'a');1 row created.SQL> insert into t_b values(1, 1, 'b');1 row created.SQL> insert into t_b values(2, '', 'c');1 row created.SQL> select * from t_a;ID N
---------- -1 aSQL> select * from t_b;ID A_ID N
---------- ---------- -1 1 b2 c
可以插入,说明外键字段是可以为空。
3.直接删除有关联子表记录的主表记录时,会报错:
SQL> delete from t_a where id=1;
delete from t_a where id=1
*
ERROR at line 1:
ORA-02292: integrity constraint (BISAL.FK_B_A) violated - child record found
4.先删除子表记录,再删除主表对应的记录,则可以执行。
SQL> delete
from t_b where id=1;1 row deleted.SQL> delete from t_a where id=1;1 row deleted.
这篇关于外键值可为空的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!