如何添加一个约束来停止具有两个相同值的列仅用于 Postgres 中的某些指定值?

How to add a constraint which stops a column having two of the same value for only some specified values in Postgres?

基本上我有一列可以有一组允许值中的一个(使用外键强制执行)。对于其中一些值,可以使用任意多行来保存该值。对于其他人,一次只能保存一行值。

架构太大,无法将其粘贴到此处,但示例如下:

name    is_president
Trump   true
Obama   false
Bush    false

所以只有一行可以有 is_president = true 而有多少行没有关系 is_president = false

我该如何强制执行此行为?我考虑过使用检查约束,例如:

CHECK((SELECT count(*) FROM presidents WHERE is_president = true) <= 1 )

但是 Postgres 不允许检查约束内的子查询。

我很确定我可以用一个函数来完成它,但由于我对模式设计很陌生,所以我对 "best practice" 解决此类问题的方法特别感兴趣,因为它看起来这一定是一个常见的情况,直觉上我认为一定有一个优雅的解决方案。

非常感谢。

您可以使用过滤(条件)唯一索引:

create unique index unq_t_is_president on t(is_president) where is_president;