Postgres:每次插入时将日期增加一天

问题描述 投票:0回答:1

我想创建一个每日随机事实表,它将每天存储事实列表。

我有一张这样的桌子

create table random_facts
(
    id           serial primary key,
    fact         text      not null,
    display_date date      not null unique default now()
);

我想在每次插入时自动增加

display_date
一天。

例如插入这样的事实后

Insert into random_facts (fact)values (unnest(ARRAY ['The shortest war in history lasted 38 minutes', 'Russell Crowe plays Maximus in the movie Gladiator', 'Australia is wider than the moon.']));

数据应该是这样的

事实 显示日期
史上最短战争持续38分钟 2024-04-26
罗素·克劳在电影《角斗士》中扮演马克西姆斯 2024-04-27
澳大利亚比月亮还宽。 2024-04-28

如何在插入的最后一行的基础上,每次插入一行时增加一天的

display_date

我正在使用 Postgres 14.5

postgresql
1个回答
0
投票

很简单,您可以使用 Unix 纪元(自 1970 年 1 月 1 日以来的秒数)为初始日期创建一个序列(以秒为单位)。例如,我们从今天开始创建一个序列

create sequence date_next_day_seq
start with 1714175999 /*valuen in seconds for today*/ 
increment 86400; /*increment of one day 24*60*60 */

然后将表定义更改为

create table random_facts
(
    id           serial primary key,
    fact         text      not null,
    display_date date      not null unique 
    default to_timestamp(nextval('date_next_day_seq'::regclass)::double precision)::date
);

在您的插入操作中您将得到

1   The shortest war in history lasted 38 minutes   2024-04-26
2   Russell Crowe plays Maximus in the movie Gladiator  2024-04-27
3   Australia is wider than the moon.   2024-04-28
© www.soinside.com 2019 - 2024. All rights reserved.