基于父记录约束子记录

时间:2014-10-21 14:39:19

标签: sql database-design

在时间表数据模型中,假设我有以下父表:

CREATE TABLE EmployeeInRole (
    employeeInRoleId PRIMARY KEY,
    employeeId,
    roleId,
    rate,
    effectiveFrom DATE, --from when can this employee assume this role
    effectiveTo DATE
);

和以下子表:

CREATE TABLE TimesheetEntry (
    startTime DATETIME,
    endTime DATETIME,
    employeeInRoleId,
    CONSTRAINT fk FOREIGN KEY (employeeInRoleId) REFERENCES EmployeeInRole (employeeInRoleId)
);

当我插入TimesheetEntry时,我想确保时间段落在父记录effectiveFrom/To的边界内。

是否可以在不使用触发器的情况下将此约束构建到DDL中,或者是否必须通过触发器或应用程序级别维护此约束?

2 个答案:

答案 0 :(得分:4)

(以下是有关Oracle的一些信息)

使用明确的DDL在Oracle中是不可能的,但您可以这样做:

create table t1 (id number primary key, date_from date, date_to date);
create table t2 (id number primary key, date_from date, date_to date, parent_id number references t1(id));
create view v as 
select t2.* from t2 
where exists (select 1 from t1 where t1.id = t2.parent_id 
  and t2.date_from between t1.date_from and t1.date_to
  and t2.date_to between t1.date_from and t1.date_to)
with check option constraint chk_v;

insert into t1 values (1, sysdate - 5, sysdate); -- OK
insert into v values (1, sysdate - 4, sysdate - 3, 1); -- OK
insert into v values (1, sysdate - 6, sysdate - 3, 1); -- ERROR (WITH CHECK OPTION where-clause violation)

V是使用CHECK OPTION

创建的可更新视图

答案 1 :(得分:1)

"是否可以在不使用触发器的情况下将此约束构建到DDL中,"

在某些RDBMS系统中可能存在,但在SQL中是不可能的。