ORACLE 外鍵約束對NULL的處理

來源:互聯網
上載者:User

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認為這樣實現是有道理的,而且它已經這樣實現了,而且我們無法改變。那麼我們能做的就是在使用複合外鍵的時候,應該更仔細的考慮是否允許外鍵列為空白的問題了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.