Oracle列由两个外键引用

时间:2014-02-25 13:55:16

标签: oracle foreign-keys

我还没有尝试过这个,它是我正在重建的90多个表模式的一部分,我想知道逻辑是否正确。
我有两个包含数据的表和第三个从它们加入PK的表:

CREATE TABLE TABLE1
(
    USER_ID NUMBER(9),
    DEPARTMENT_ID NUMBER(9),
    DESK_ID NUMBER(9),
    FULLNAME VARCHAR2(12),
    CONSTRAINT PK_TABLE1 PRIMARY KEY (USER_ID, DEPARTMENT_ID, DESK_ID)
);

CREATE TABLE TABLE2
(
    USER_ID NUMBER(9),
    BUILDING_ID NUMBER(9),
    PARKING_ID NUMBER(9),
    LICENSE_PLATE VARCHAR2(10),
    CONSTRAINT PK_TABLE2 PRIMARY KEY (USER_ID, BUILDING_ID, PARKING_ID)
);

CREATE TABLE TABLE3
(
    USER_ID NUMBER(9),
    DEPARTMENT_ID NUMBER(9),
    DESK_ID NUMBER(9),
    BUILDING_ID NUMBER(9),
    PARKING_ID NUMBER(9),
    CONSTRAINT PK_TABLE3 PRIMARY KEY (USER_ID, DEPARTMENT_ID, DESK_ID, BUILDING_ID, PARKING_ID),
    CONSTRAINT FK_TABLE3_T1 FOREIGN KEY (USER_ID, DEPARTMENT_ID, DESK_ID) REFERENCES TABLE1(USER_ID, DEPARTMENT_ID, DESK_ID),
    CONSTRAINT FK_TABLE3_T2 FOREIGN KEY (USER_ID, BUILDING_ID, PARKING_ID) REFERENCES TABLE2(USER_ID, BUILDING_ID, PARKING_ID)
);

是不是?同一列TABLE3.USER_ID可以是两个FK的一部分吗? 感谢

1 个答案:

答案 0 :(得分:0)

是的,即使列列相同,也可以。

试试这个:

CREATE TABLE T1
(C1   NUMBER   PRIMARY KEY);

CREATE TABLE T2
(C1   NUMBER   PRIMARY KEY);

CREATE TABLE T3
(C1   NUMBER   PRIMARY KEY);

用一些值填充T1和T2:

INSERT INTO T1 VALUES(1);
INSERT INTO T1 VALUES(2);

INSERT INTO T2 VALUES(1);
INSERT INTO T2 VALUES(3);

从T3到T1和T2创建两个相同的约束:

ALTER TABLE T3
ADD CONSTRAINT FK1 FOREIGN KEY (C1) REFERENCES T1(C1);

ALTER TABLE T3
ADD CONSTRAINT FK2 FOREIGN KEY (C1) REFERENCES T2(C1);

现在......

INSERT INTO T3 VALUES(1);   -- Succeeds (1 is in both T1 and T2)
INSERT INTO T3 VALUES(2);   -- Fails (2 is only in T1 and violates FK2)

清洁环境:

DROP TABLE T3 PURGE;
DROP TABLE T1 PURGE;
DROP TABLE T2 PURGE;

我希望这可以帮助你...