PostgreSQL - 对日期列部分强制执行唯一约束

Blo*_*tac 5 postgresql constraint

我试图在带有数据列的表上强制执行唯一的月份和年份组合。例如

create table foo
(
    mydate date
);
Run Code Online (Sandbox Code Playgroud)

我想强制每月和每年只有一行有效,即

insert into foo values ('2018-01-01'); -- valid
insert into foo values ('2018-01-15'); -- Wouldn't be valid as one row already exists for January 2018
insert into foo values ('2018-02-15'); -- valid
Run Code Online (Sandbox Code Playgroud)

天部分无关紧要。应用程序应该只插入当月的第一天,但​​只要每月和每年只有一行就没关系。

在 Oracle 或 SQL Server 中,我将能够在基于函数的唯一索引中使用确定性函数,因此我可以使用 date_trunc('month',mydate) 的结果,它会强制执行我想要的,但这似乎不是在 PostgreSQL 中是可能的。

我似乎也无法创建虚拟/计算/计算字段,因此也不能以这种方式强制执行。

我应该如何强制执行此约束?

我真的在做一些愚蠢的事情吗?

ype*_*eᵀᴹ 7

也使用EXTRACT(year/month ...)作品:

create unique index year_month_uq 
  on foo 
  ( extract(year from mydate), 
    extract(month from mydate)
  ) ;
Run Code Online (Sandbox Code Playgroud)