Postgresql:如何引用具有多个唯一主键的表

时间:2018-05-31 21:31:08

标签: sql postgresql unique-constraint

尝试在postgresql中创建表,无法创建ftotal获取 ERROR: there is no unique constraint matching given keys for referenced table "cur"

CREATE TABLE con (
 con_code CHAR (3) PRIMARY KEY  NOT NULL,
 con_name VARCHAR (100)             NOT NULL
);

CREATE TABLE cur (
 cur_code   CHAR (3)        NOT NULL,
 cur_name   VARCHAR (100)   NOT NULL,
 con_code   CHAR (3)        NOT NULL,
 UNIQUE (cur_code,con_code),
 PRIMARY KEY (cur_code, con_code),
 FOREIGN KEY (con_code) REFERENCES con (con_code)
);

CREATE TABLE ftotal (
    eff_date    DATE        NOT NULL,
    con         CHAR(3) NOT NULL,
    cur         CHAR(3) NOT NULL,
    PRIMARY KEY (eff_date,con,cur),
    FOREIGN KEY (con) REFERENCES con (con_code),
    FOREIGN KEY (cur) REFERENCES cur (cur_code)
);

1 个答案:

答案 0 :(得分:3)

外键引用需要是整个主键:

CREATE TABLE ftotal (
    eff_date    DATE NOT NULL,
    con         CHAR(3) NOT NULL,
    cur         CHAR(3) NOT NULL,
    PRIMARY KEY (eff_date, con, cur),
    FOREIGN KEY (con) REFERENCES con (con_code),
    FOREIGN KEY (cur, con) REFERENCES cur (cur_code, con_ode)
);