【问题标题】:constrainging database with alternate foreign keys用备用外键约束数据库
【发布时间】:2012-01-20 19:33:22
【问题描述】:

我有一个数据库表,用作系统之间的接口。我给它写信,他们读它。我的表中有一个引用我的用户表的外键。

现在界面变得越来越复杂。我现在对不引用用户表的接口表有另一种用途。我当然可以放松对用户表的外键约束。

我想要做的是有一个约束状态,要么满足这个外键,要么满足这个其他键(在不同的列中)。这可能吗?

我有一个 oracle 数据库。

【问题讨论】:

    标签: sql oracle ddl


    【解决方案1】:

    您可以将两列都声明为可为空,并创建一个检查约束以确保两列中的一列不为空。

    例如,如果我为教授和讲师设置了单独的表格,并且我想对班级进行建模,以便班级可以有教授或讲师但不能同时拥有,我可以这样做

    SQL> ed
    Wrote file afiedt.buf
    
      1  create table professor(
      2    professor_id number primary key
      3* )
    SQL> /
    
    Table created.
    
    SQL> create table lecturer(
      2    lecturer_id number primary key
      3  );
    
    Table created.
    
    SQL> create table class(
      2    class_id number primary key,
      3    lecturer_id number references lecturer( lecturer_id ),
      4    professor_id number references professor( professor_id ),
      5    check( (lecturer_id is null and professor_id is not null) or
      6           (lecturer_id is not null and professor_id is null) )
      7  );
    
    Table created.
    
    SQL> insert into professor values( 1 );
    
    1 row created.
    
    SQL> insert into lecturer values( 20 );
    
    1 row created.
    
    SQL> insert into class values( 1, 20, null );
    
    1 row created.
    
    SQL> insert into class values( 2, null, 1 );
    
    1 row created.
    
    SQL> insert into class values( 3, 20, 1 );
    insert into class values( 3, 20, 1 )
    *
    ERROR at line 1:
    ORA-02290: check constraint (SCOTT.SYS_C0014175) violated
    

    当然,从数据建模的角度来看,创建单个 INSTRUCTOR 表和 INSTRUCTOR_TYPE(可以是 LECTURERPROFESSOR)并创建 CLASS具有INSTRUCTOR 表的不可为空外键的表。

    【讨论】:

      【解决方案2】:

      我会为新的接口要求创建一个不同的表。约束的一个差异只会导致另一个差异。

      然后我会考虑是否应该创建一个视图,并让应用程序软件从视图中读取而不是从基表中读取。

      【讨论】:

      • 创建视图是最好的选择
      【解决方案3】:

      不,这是不可能的。您可以将相当于链接到一个或其他表的三级键表放在一起,但它非常混乱和脆弱。

      相反,我强烈建议您重新审视您的集成策略,因为您当前的集成策略似乎无法按照您需要的方式进行调整。

      【讨论】:

      • 我同意这是一个杂牌。但这比暴露两张桌子更像是一种杂物吗?
      猜你喜欢
      • 2013-12-17
      • 2018-01-23
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2013-04-07
      • 2012-08-15
      • 2020-10-30
      • 2011-04-09
      相关资源
      最近更新 更多