PostgreSQL引用错误

时间:2016-06-16 19:12:39

标签: sql postgresql postgresql-9.4

我有一个房东表和一张清单表。在创建列表时,我收到了这个错误。

ERROR: there is no unique constraint matching given keys for referenced table "t_property_landlord"
SQL state: 42830

create table if not exists t_listing(
    rental_listing_id BIGSERIAL primary key,
    landlord_id BIGSERIAL references t_property_landlord(landlord_id),
    available varchar(25),
    rent numeric,
    deposit numeric,
    description text,
    term varchar(25),
    pet boolean,
    feature JSON,
    post_ts date,
    view numeric,
    create_ts timestamp default now()
);

这是房东表。

create table if not exists t_property_landlord(
    landlord_id BIGSERIAL,
    email varchar(100) references t_user(email),
    property_id BIGSERIAL references t_property(property_id),
    change_ts timestamp default now(),
    active boolean default true,
    primary key(email,property_id)
);

我尝试创建create_ts,并引用landlord_id,使那些你独特但仍无法正常工作。有人可以看看,让我知道我做错了什么?我正在使用PostgreSQL 9.4

感谢,

1 个答案:

答案 0 :(得分:1)

t_property_landlord.landlord_id不是一个独特的列。它需要是外键才能引用它。有关如何声明一个的信息,请参阅此处:https://www.postgresql.org/docs/8.1/static/ddl-constraints.html

您的t_property_landlord表应如下所示:

create table if not exists t_property_landlord(
    landlord_id BIGSERIAL UNIQUE NOT NULL,
    email varchar(100) references t_user(email),
    property_id BIGSERIAL references t_property(property_id),
    change_ts timestamp default now(),
    active boolean default true,
    primary key(email,property_id)
);

最后,您可能想要再次查看您的设计,因为您尝试将外键引用作为另一个表中不是该表的主键的列。通常,外键应该引用主键。