PostgresQL 创建自动填充另一列的列?

PostgresSQL creating column that automatically fill another column?

我是 postgres 的新手,所以我不知道这是否可行。

我想在 table 中创建一个可以自动填充下一列的列。 例如:

CREATE TABLE table_name (
    id bigserial NOT NULL,
    inspectionDate date NOT NULL,
    next_inspection_date date NOT NULL
);

那么,如果 'inspectionDate' 栏是今天填充的,比如 2020-06-28,'next_inspection_date' 栏是否可以自动填充 3 年后(2023-06-28)的日期?

您可以使用生成的列:

CREATE TABLE table_name (
    id bigserial NOT NULL,
    inspectionDate date NOT NULL,
    next_inspection_date date NOT NULL
        GENERATED ALWAYS AS (inspectionDate + INTERVAL '3 year') STORED
);

生成的列应自动填充距 inspectionDate 列 3 年的日期,只要有插入或更新。

如果您使用的是 PostgreSQL 12,那么您可以使用生成的列

https://pgdash.io/blog/postgres-12-generated-columns.html

https://severalnines.com/database-blog/overview-generated-columns-postgresql