【问题标题】:Use PK serial column value as default for another non-null column使用 PK 序列列值作为另一个非空列的默认值
【发布时间】:2019-09-09 06:14:56
【问题描述】:

我有一个表,其自身具有简单的层次父子关系。我没有使用嵌套集,而是添加了一个 root_id 列,这样我就可以使用单个查询加载单个根的所有后代。

create table tree (
    id          serial                  primary key,
    root_id     int     not null        default id,  -- error
    parent_id   int,
    ...
);

我想将该列设为not null,但新根的值将是根自己的主键值,在插入之前不可用。有什么方法可以将行的主键值用作root_id 列的默认值?

【问题讨论】:

    标签: postgresql default-value


    【解决方案1】:

    在描述表格以查看id 列的默认值并猜测语法后,我发现您可以使用序列的当前值作为默认值。

    root_id     int     not null        default currval('tree_id_seq'::regclass)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-03
      • 2013-05-19
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2013-09-08
      • 2014-10-02
      • 2012-12-01
      相关资源
      最近更新 更多