Oracle處理NULL的特點。簡單的說,就是如果多個列構成了唯一,且其中包含一個以上的NULL,那麼Oracle會要求不為NULL的列保持唯一。
但是在外鍵處理時,卻不是這種方法:
SQL> create table t_p (id number, name varchar2(30), constraint pk_t_p primary k
ey (id, name));
Table created.
SQL> create table t_c (id number, f_id number, f_name varchar2(30),
2 constraint fk_t_c foreign key (f_id, f_name) references t_p);
Table created.
SQL> insert into t_p values (1, 'a');
1 row created.
SQL> insert into t_c values (1, 1, 'a');
1 row created.
SQL> insert into t_c values (1, 1, 'b');
insert into t_c values (1, 1, 'b')
*
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.FK_T_C) violated - parent key not found
SQL> insert into t_c values (1, null, 'b');
1 row created.
SQL> insert into t_c values (1, null, 'b');
1 row created.
SQL> select * from t_c;
ID F_ID F_NAME
---------- ---------- ------------------------------
1 1 a
1 b
1 b
SQL>
可以看到,F_ID列為空白,使得Oracle不再檢查其他列是否滿足外鍵約束的條件,而使得這條記錄直接插入到子表中。
由於一般組合外鍵使用的相對比較少,所以這個問題以前還真沒有注意過,這次在看文檔時,才看到這個描述。
這裡不討論這樣的實現是否有道理,至少Oracle認為這樣實現是有道理的,而且它已經這樣實現了,而且我們無法改變。那麼我們能做的就是在使用複合外鍵的時候,應該更仔細的考慮是否允許外鍵列為空白的問題了。