从oracle中的两个不同的表主键创建复合外键

时间:2016-07-17 13:24:28

标签: oracle foreign-keys

表1:

tid(主键) //这里没有外键

表2:

sid(主键) //这里也没有外键

表3:

 Tid
 Sid
 iid(primary key)
 foreign key(Tid,Sid) references table1(tid).table2(sid)

 In table3 i want to make a composite foreign key or composite foreign key constraint but failed . there are many questions related to this .But none of them seems helpful to me . How can i do that ? Is it valid ? Then what is the syntax of making composite foreign key from two different tables primary key   

1 个答案:

答案 0 :(得分:1)

不可能在不同的表上使用单个外键引用字段,这根本没有意义。两个或多个字段的外键意味着字段值的组合必须在引用表的单个记录上匹配,如果引用的字段位于不同的表上,则无法完成此操作。

您可以做的是为两个表创建两个不同的外键,如下所示:

CREATE TABLE table3(
    iid NUMBER,
    Tid NUMBER,
    Sid NUMBER,
    CONSTRAINT pk    PRIMARY KEY (iid) USING INDEX TABLESPACE idx,
    CONSTRAINT fk001 FOREIGN KEY (tid) REFERENCES table1(tid),
    CONSTRAINT fk002 FOREIGN KEY (sid) REFERENCES table2(sid)
);