PostgreSQL 引用错误

PostgreSQL referencing error

我有房东table和房源table。在创建我的列表时 table,我收到了这个错误。

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()
);

这里是楼主table.

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

谢谢,

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

您的 t_property_landlord table 应如下所示:

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)
);

最后,您可能想重新审视一下您的设计,因为您正试图使外键引用另一个 table 中的列,而不是那个 table 的列首要的关键。通常,外键应该引用主键。