【问题标题】:PostgreSQL: NULL value in foreign key columnPostgreSQL:外键列中的 NULL 值
【发布时间】:2014-06-13 02:23:02
【问题描述】:

在我的 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,它不允许这样做。

我想要的是一个可选(或可为空)外键约束@​​987654323@ (fk_quotation_receipt_id) → quotations (receipt_id)。我在官方 PgSQL 文档中找不到任何提示,其他用户发布的类似问题已经很老了。

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

【问题讨论】:

    标签: postgresql foreign-keys


    【解决方案1】:

    在更正缺少的逗号后在 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);
    

    Confirmation 将包括:

    INSERT 0 1
    

    【讨论】:

    • 缺少逗号不是问题(我只是在复制时忘记了它,grrrrr)。事实证明,客户端代码添加了 0 而不是 NULL,由于这是一个准备好的语句,我在日志中没有看到它。不过非常感谢您的回答。
    猜你喜欢
    • 2015-03-28
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 2020-08-03
    • 1970-01-01
    • 2019-07-23
    相关资源
    最近更新 更多