我正在尝试执行约束,该约束将检查table1中的数据不能早于数据表2。例如
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 :(得分:1)
表1 ID ID的主键及其对Table2 ID2的参考。 Table2的主键是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.id2
和t1.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