错误:没有唯一约束匹配给定引用表的键

时间:2015-10-30 13:18:19

标签: sql postgresql foreign-keys database-schema ddl

出于某种原因,我的代码中出现了错误*。我对PostgreSQL很新,而且只是SQL。导致此错误的原因是什么?

*没有唯一约束匹配给定引用表" tech"。

的给定键
BEGIN;

CREATE TABLE Person (
    person_id   SERIAL PRIMARY KEY,
    firstname   VARCHAR(128),
    lastname    VARCHAR(128),
    email_adr   VARCHAR(128),

    UNIQUE(person_id, email_adr)
);

CREATE TABLE Phone (
    person_id   INT REFERENCES Person(person_id),
    phone_nr    INT PRIMARY KEY,

    UNIQUE(phone_nr)
);


CREATE TABLE Tech (
    tech_id INT REFERENCES Person(person_id),
    username    VARCHAR(80) PRIMARY KEY,
    password    VARCHAR(80) NOT NULL,
    location    Varchar(128),

    UNIQUE(username, tech_id)
);

CREATE TABLE Customer (
    customer_id    INT REFERENCES Persons(person_id),
    addresse       VARCHAR(255) NOT NULL,

    UNIQUE(customer_id)
);

CREATE TABLE Task (
    task_id     SERIAL PRIMARY KEY,
    payment     MONEY,
    tech        INT REFERENCES Tech(tech_id)         NOT NULL,
    customer    INT REFERENCES Customer(customer_id) NOT NULL,
    start_date  DATE                                 NOT NULL,
    end_dato    DATE,

    UNIQUE(tech, customer, start_date, end_date)
);

COMMIT;

2 个答案:

答案 0 :(得分:2)

在表Task中,您试图通过Tech引用表tech_id。为此,您必须在UNIQUE CONSTRAINT中将tech_id添加到Tech。 现在在表Tech中,您UNIQUE(username, tech_id)表示tech_id列中的值可以加倍Ex。

Tech
-------------------------------
tech_id     username,    ....
------------------------------
1           'John'
2           'Tony'
1           'Nataly'

实际上,更好的想法是按PRIMARY KEY设置引用,因此在您的情况下username位于表Tech中。

如果您希望以相关方式保留结构,则只需在UNIQUE(tech_id)列中添加Tech

答案 1 :(得分:0)

您如何看待此代码?

BEGIN;

CREATE TABLE Person (
    person_id   SERIAL PRIMARY KEY,
    firstname   VARCHAR(128),
    lastname    VARCHAR(128),
    email_adr   VARCHAR(128),

    UNIQUE(person_id),
    UNIQUE(email_adr)
);

CREATE TABLE Phone (
    person_id   INT,
    phone_nr    INT PRIMARY KEY,
);


CREATE TABLE Tech (
    tech_id INT,
    username    VARCHAR(80) PRIMARY KEY,
    password    VARCHAR(80) NOT NULL,
    location    Varchar(128),

    FOREIGN KEY(tech_id) REFERENCES Person(person_id),
    UNIQUE(username),
    UNIQUE(tech_id)
);

CREATE TABLE Customer (
    customer_id    INT REFERENCES Persons(person_id),
    addresse       VARCHAR(255) NOT NULL,

    FOREIGN KEY(tech_id) REFERENCES Person(person_id),
    UNIQUE(customer_id)
);

CREATE TABLE Task (
    task_id     SERIAL PRIMARY KEY,
    payment     MONEY,
    tech        varchar(80) REFERENCES Tech(username)       NOT NULL,
    customer    INT        REFERENCES Customer(customer_id) NOT NULL,
    start_date  DATE                                 NOT NULL,
    end_dato    DATE,

    UNIQUE(tech, customer, start_date, end_date)
);

COMMIT;