2016-05-17 28 views
1

我有兩個具有二元關係的表,它們相互關聯,如何在這些表中插入值?將值插入到具有約束條件的表中

create table t1 
(
    cola_1 integer constraint t1_cola_1_pk primary key, 
    cola_2 integer 
); 

create table t2 
(
    colb_1 integer constraint t2_colb_1_pk primary key, 
    colb_2 integer constraint t2_colb_2_fk references t1(cola_1) 
); 

alter table t1 
modify cola_2 constraint t1_cola_2_fk references t2(colb_1); 

如何將值插入t1表中?

+2

在同一事務中插入t1和t2。 – jarlh

+4

循環引用是一個糟糕的主意。我的猜測是,這是一個錯誤是表設計 –

+0

即使你使用延遲約束來解決你的問題,你將來也會遇到問題。最好的解決方案是有一張桌子而不是兩張桌子。 – ibre5041

回答

4

您可以創建DEFERRED限制,讓他們檢查在提交時:

SQL> create table t1 
    2 (
    3 cola_1 integer constraint t1_cola_1_pk primary key, 
    4 cola_2 integer 
    5 ); 

Table created. 

SQL> create table t2 
    2 (
    3 colb_1 integer constraint t2_colb_1_pk primary key, 
    4 colb_2 integer constraint t2_colb_2_fk references t1(cola_1) INITIALLY DEFERRED 
    5 ); 

Table created. 

SQL> alter table t1 
    2 modify cola_2 constraint t1_cola_2_fk references t2(colb_1) INITIALLY DEFERRED; 

Table altered. 

你可以做運行insert報表,而無需任何檢查:

SQL> insert into t2(colb_1, colb_2) values (10, 20); 

1 row created. 

SQL> insert into t1(cola_1, cola_2) values (40, 40); 

1 row created. 

SQL> commit; 
commit 
* 
ERROR at line 1: 
ORA-02091: transaction rolled back 
ORA-02291: integrity constraint (ALEK.T2_COLB_2_FK) violated - parent key not 
found 

當您嘗試執行檢查commit;在這種情況下,我有一個失敗和一個rollback,因爲我試圖插入錯誤的值。 如果我插入正確的數據,甚至commit是確定的:

SQL> insert into t2(colb_1, colb_2) values (10, 10); 

1 row created. 

SQL> insert into t1(cola_1, cola_2) values (10, 10); 

1 row created. 

SQL> commit; 

Commit complete. 

SQL> 

但是,如果沒有一個強有力的理由,創建表遞歸引用可能不是一個好主意;大概你可以改變你的DB設計來避免這種情況