Oracle - 在多个表中有外键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2062310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 19:48:38  来源:igfitidea点击:

Oracle - Having foreign keys in more than one table

sqloracle

提问by James Thompson

I'm not sure if one can do this but I need to have foreign key reference 2 tables.

我不确定是否可以做到这一点,但我需要有外键引用 2 个表。

Table1 has 2 columns (A PK, B)
Table2 has 2 columns (C PK, D)

Table3 has 3 columns (A PK, B PK, E) and is made up of the first two table.

表 3 有 3 列(A PK、B PK、E),由前两个表组成。

What I am hoping to do is something like the following:

我希望做的是如下所示:

create table Table3     
(
  A Varchar2 (4),   
  C Varchar2 (10),  
  E Char (1),
    constraint PK_A_C primary key (A, C),
    CONSTRAINT FK_A_C
   FOREIGN KEY (A, C) 
   REFERENCES (Table1.A, Table2.B)
);

I hope that this makes some sort of sense.

我希望这有点道理。

Thanks

谢谢

James

詹姆士

回答by Bill Karwin

A given foreign key constraint describes a relationship from one child table to one parent table.

给定的外键约束描述了从一个子表到一个父表的关系。

You can, however, have two foreign key constraints, each pointing to the respective table:

但是,您可以有两个外键约束,每个都指向相应的表:

create table Table3     
(
  A Varchar2 (4),   
  C Varchar2 (10),  
  E Char (1),
    constraint PK_A_C primary key (A, C),
    CONSTRAINT FK_A
     FOREIGN KEY (A) 
     REFERENCES Table1(A),
    CONSTRAINT FK_B
     FOREIGN KEY (C) 
     REFERENCES Table2(B)
);

回答by OMG Ponies

Use:

用:

CONSTRAINT fk_a FOREIGN KEY (a) REFERENCES TABLE1(a)
CONSTRAINT fk_b FOREIGN KEY (c) REFERENCES TABLE2(b)

Reference:

参考: