PostgreSQL:外键列中的NULL值

时间:2014-04-27 16:23:36

标签: postgresql foreign-keys

在我的PostgreSQL数据库中,我有以下表格(简化):

CREATE TABLE quotations (
  receipt_id bigint NOT NULL PRIMARY KEY
);

CREATE TABLE order_confirmations (
  receipt_id bigint NOT NULL PRIMARY KEY
  fk_quotation_receipt_id bigint REFERENCES quotations (receipt_id)
);

我现在的问题如下:

我有与先前报价相关的订单(这很好'因为我可以将这样的订单附加到使用FK字段引用的报价单),但我也有从头开始的订单没有匹配报价。如果数据库允许我,FK字段将为NULL。不幸的是,由于违反外键约束,我在INSERT语句中尝试将fk_quotation_receipt_id设置为NULL时出现错误

在设计这些表时,我仍然使用PgSQL 8.2,它允许NULL值。现在我已经有了9.1.6,这是不允许的。

我希望的是可选(或可空)外键约束order_confirmations(fk_quotation_receipt_id)→引用(receipt_id)。我在官方PgSQL文档中找不到任何提示,其他用户发布的类似问题已经很老了。

感谢您提供任何有用的提示。

1 个答案:

答案 0 :(得分:23)

在纠正丢失的逗号后,在9.3中为我工作。我相信它也适用于9.1

create table quotations (
    receipt_id bigint not null primary key
);

create table order_confirmations (
    receipt_id bigint not null primary key,
    fk_quotation_receipt_id bigint references quotations (receipt_id)
);

insert into order_confirmations (receipt_id, fk_quotation_receipt_id) values 
    (1, null);
INSERT 0 1
相关问题