针对非PK列集创建外键

时间:2014-04-07 11:48:15

标签: sql oracle oracle10g oracle-xe

我想针对不属于父表主键的两列创建一个外键(我明白这是可能的)但是我总是碰到这个墙:

  

ORA-02270此列列表没有匹配的唯一或主键

父表是这样的:

CREATE TABLE FOO_PERSONAL (
    FOO_IMPORTACION_ID NUMBER(*,0) NOT NULL,
    TALLER_ID NUMBER(*,0) NOT NULL,
    PERSONAL_ID NUMBER(*,0) NOT NULL,

    NOMBRE_PERSONA VARCHAR2(255 CHAR) NOT NULL,

    CONSTRAINT FOO_PERSONAL_PK PRIMARY KEY (FOO_IMPORTACION_ID, TALLER_ID, PERSONAL_ID)
);

-- Not the right syntax?
CREATE UNIQUE INDEX FOO_PERSONAL_UQ1 ON FOO_PERSONAL (FOO_IMPORTACION_ID, PERSONAL_ID);

...和子表是:

CREATE TABLE FOO_CARGO (
    FOO_IMPORTACION_ID NUMBER(*,0) NOT NULL,
    PERSONAL_ID NUMBER(*,0) NOT NULL,
    CARGO_ID NUMBER(*,0) NOT NULL,

    CARGO VARCHAR2(255 CHAR) NOT NULL,

    CONSTRAINT FOO_CARGO_PK PRIMARY KEY (FOO_IMPORTACION_ID, PERSONAL_ID, CARGO_ID),

    CONSTRAINT FOO_CARGO_FK1 FOREIGN KEY (FOO_IMPORTACION_ID, PERSONAL_ID)
    REFERENCES FOO_PERSONAL (FOO_IMPORTACION_ID, PERSONAL_ID)
    -- ^ ORA-02270
    ON DELETE CASCADE
    ENABLE
);

我错过了什么?

1 个答案:

答案 0 :(得分:1)

您需要一个独特的约束,而不仅仅是唯一的索引

CREATE TABLE FOO_PERSONAL (
    FOO_IMPORTACION_ID NUMBER(*,0) NOT NULL,
    TALLER_ID NUMBER(*,0) NOT NULL,
    PERSONAL_ID NUMBER(*,0) NOT NULL,

    NOMBRE_PERSONA VARCHAR2(255 CHAR) NOT NULL,

    CONSTRAINT FOO_PERSONAL_PK PRIMARY KEY (FOO_IMPORTACION_ID, TALLER_ID, PERSONAL_ID),
    CONSTRAINT FOO_PERSONAL_UQ1 UNIQUE (FOO_IMPORTACION_ID, PERSONAL_ID)
);