PostgreSQL。约束只允许许多可能值中的一个

PostgreSQL. constraint allowing only one of many possible values

我的状态是这样的:startedcalculatedfinished 我需要一个约束,在 table.

中只允许一个 NOT finished 状态

这是允许的:

+----+----------+
| id |  status  |
+----+----------+
|  1 | finished |
|  2 | finished |
|  3 | started  |
+----+----------+
+----+------------+
| id |   status   |
+----+------------+
|  1 | finished   |
|  2 | finished   |
|  3 | calculated |
+----+------------+

由于两个未完成状态而被禁止:

+----+------------+
| id |   status   |
+----+------------+
|  1 | finished   |
|  2 | finished   |
|  3 | calculated |
|  4 | started    |
+----+------------+

您可以使用过滤唯一索引:

create unique index myindex
    on mytable ((1)) 
    where (status <> 'finished')

诀窍是将固定值而不是列名传递给索引的 on 子句(我们需要两个括号,以便 Postgres 将其作为表达式求值)。这与过滤“完成”以外的状态的 where 子句相结合,以实现您想要的逻辑。

Demo on DB Fiddle