PostgreSQL:外键列中的NULL值

Nep*_*muk 33 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文档中找不到任何提示,其他用户发布的类似问题已经很老了.

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

Clo*_*eto 29

在纠正丢失的逗号后,在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);
Run Code Online (Sandbox Code Playgroud)

  • 丢失的逗号不是问题(我在复制时忘了它,grrrrr).原来,客户端代码添加了0而不是NULL,因为这是一个准备好的语句,我没有在日志中看到它.然而,对你的回答而言,还是很多. (11认同)