Hi,
我有两个表,其中一个表中记录了两种类型的数据,例如学生和老师两种类型的记录,另一个表的其中一个字段只能为前一个表的老师字段,因此,我想在表设计时期把这个字段的值限定为前一个表的老师记录ID内。请问如何限定?
我考虑过外关键字,好像不能满足要求;也考虑过约束,但不知道约束如何支持动态数据约定;对您的任何有益的提示或建议均表示衷心的感谢!

解决方案 »

  1.   

    如果老师和学生在第一个表中是一列的话,在第二个表建写触发器吧
    create or replace trigger xxxxxx
    before insert or update
    is
    cont number;
    begin
    select count(*) into cont
    from 表1 where 列=new.老师;
    if count(*)=0 then
    raise_application_error(-20001,'');
    end if;
    end xxxxxxxxx
      

  2.   

    有个简单的办法。
    你先别管第二个表的老师ID,先允许任意记录插入。在你过程或SQL完加入一条删除语句将不在第一张中的老师ID删除就OK了呀
      

  3.   

    写触发器其实简单点。用CHECK的话,这样做:
    OPER@tl> select * from test;        ID NAMES
    ---------- --------------------
             1 老师
              2 学生
              3 老师OPER@tl> create table test2(id number,sex varchar2(10));表已创建。OPER@tl> create view t3 as
      2  select * from test2
      3  where id in(select id from test where names='老师')
      4  with check option;视图已创建。OPER@tl> insert into t3 values(1,'男');已创建 1 行。OPER@tl> insert into t3 values(2,'男');
    insert into t3 values(2,'男')
                *
    第 1 行出现错误:
    ORA-01402: 视图 WITH CHECK OPTIDN where 子句违规
    OPER@tl> insert into t3 values(3,'男');已创建 1 行。OPER@tl> insert into t3 values(4,'男');
    insert into t3 values(4,'男')
                *
    第 1 行出现错误:
    ORA-01402: 视图 WITH CHECK OPTIDN where 子句违规
    OPER@tl> commit;提交完成。OPER@tl> select * from test2;        ID SEX
    ---------- --------------------
             1 男
              3 男