外键值可为空

来源:互联网 发布:win10有网络不能上网 编辑:程序博客网 时间:2024/03/29 21:19

从感官上,外键用于限制主子表的关联关系,是一种强关联关系,那么子表的外键值不应该为空,而是都会关联到主表对应的记录上,但实际上,至少在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 b         2            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.
0 0