【问题标题】:Constraining Child Record Based on Parent Record基于父记录约束子记录
【发布时间】:2014-10-21 14:39:18
【问题描述】:

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

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 中,还是我必须通过触发器或在应用程序级别维护此约束?

【问题讨论】:

    标签: sql database-design


    【解决方案1】:

    (这里仅提供一些关于 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 创建的可更新视图

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 2012-07-02
        • 2014-07-14
        • 1970-01-01
        • 2019-02-21
        • 1970-01-01
        • 2017-07-24
        相关资源
        最近更新 更多