我可以在Oracle中使用复合主键作为外键吗?

时间:2014-06-02 02:55:18

标签: sql oracle foreign-keys primary-key composite-primary-key

我只是想知道是否可以将表A中的表A复合主键用作外键。

CREATE TABLE A(
   ID INT,
   COD INT,
   CONSTRAINT  PK_INF PRIMARY KEY (ID, COD),
);

CREATE TABLE B(
   REF_NUMBER INT,
   NAME VARCHAR(30),
   CONSTRAINT  FK_INF FOREIGN KEY (REF_NUMBER) REFERENCES A(PK_INF) <- is this correct?
);

提前致谢。

1 个答案:

答案 0 :(得分:1)

您的问题的答案是“是”,您可以使用复合主键进行外键引用。但是,你需要两列。像这样:

CREATE TABLE A(
   ID INT,
   COD INT,
   CONSTRAINT  PK_INF PRIMARY KEY (ID, COD),
);

CREATE TABLE B(
   REF_ID INT,
   REF_CODINT,
   NAME VARCHAR(30),
   CONSTRAINT  FK_INF FOREIGN KEY (REF_ID, REF_COD) REFERENCES A(ID, COD) <- is this correct?
);