2015-11-06 114 views
0

我試圖做一個約束,它將檢查table1中的數據不能早於那個數據table2。例如。約束,引用其他表

Table1 
ID Date 
1  2015-05-06 
2  2015-05-07 
3  2015-05-08 

Table2 
    ID  ID2  Date 
    434  1  2015-05-05 
    435  2  2015-05-06 
    436  3  2015-05-07 

Table1 join Table2 on table1.ID=table2.id2 

現在我想要改變table1與約束,它會是怎樣的?

+0

它看起來像表2 –

+0

觸發我不能用支票條款做到這一點?當然,我在插入數據時需要檢查 – maciek2791

+0

table1和table2之間是否存在一對一的關係?每個表的主鍵和外鍵是什麼? – Ben

回答

1

表1 ID ID的主鍵,它引用了Table2 ID2。表2的主鍵是ID

從您的數據模型你自己的描述是這樣的:

create table t2 (
    id number 
, id2 number 
, dt date 
, constraint pk_t2 primary key (id) 
, constraint uk_t2_id2 unique (id2) 
    ); 

insert into t2 values (434, 1, date '2015-05-05'); 
insert into t2 values (435, 2, date '2015-05-06'); 
insert into t2 values (436, 3, date '2015-05-07'); 

create table t1 ( 
    id number 
, dt date 
, constraint pk_t1 primary key (id) 
, constraint fx_t1_t2 foreign key (id) 
    references t2 (id2) 
    ); 

insert into t1 values (1, date '2015-05-06'); 
insert into t1 values (2, date '2015-05-07'); 
insert into t1 values (3, date '2015-05-08'); 

由於公共密鑰(t2.id2t1.id)是唯一的兩個表中的方法強制執行此約束是合併兩個表並添加約束。

你的數據模型相當於:

create table t1 (
    id number 
, id2 number 
, date1 date 
, date2 date 
, constraint pk_t1 primary key (id) 
, constraint uk_t1 unique (id2) 
, constraint chk_t1_dates 
    check (date1 < date2) 
    ); 

insert into t1 values (434, 1, date '2015-05-05', date '2015-05-06'); 
insert into t1 values (435, 2, date '2015-05-06', date '2015-05-07'); 
insert into t1 values (436, 3, date '2015-05-07', date '2015-05-08'); 

沒有爲id2沒有實際需要...

如果再需要的數據是分開的,你可以創建兩個視圖來表示的表

SQL> create or replace view v_t1 as 
    2 select id2 as id, date1 
    3 from t1; 

View created. 

SQL> 
SQL> create or replace view v_t2 as 
    2 select id, id2, date2 
    3 from t1; 

View created. 

SQL> select * from v_t1; 

     ID DATE1 
---------- ---------- 
     1 2015-05-05 
     2 2015-05-06 
     3 2015-05-07 

SQL> select * from v_t2; 

     ID  ID2 DATE2 
---------- ---------- ---------- 
     434   1 2015-05-06 
     435   2 2015-05-07 
     436   3 2015-05-08 
+0

謝謝本! :) – maciek2791