PostgreSQL。仅允许多个可能值中的一个的约束
我的状态如下:PostgreSQL。仅允许多个可能值中的一个的约束,sql,postgresql,where-clause,unique-constraint,unique-index,Sql,Postgresql,Where Clause,Unique Constraint,Unique Index,我的状态如下:已开始,已计算,已完成 我需要一个约束,该约束只允许表中有一个未完成状态 这是允许的: +----+----------+ | id | status | +----+----------+ | 1 | finished | | 2 | finished | | 3 | started | +----+----------+ +----+------------+ | id | status | +----+------------+ | 1 | finis
已开始
,已计算
,已完成
我需要一个约束,该约束只允许表中有一个未完成状态
这是允许的:
+----+----------+
| id | status |
+----+----------+
| 1 | finished |
| 2 | finished |
| 3 | started |
+----+----------+
+----+------------+
| id | status |
+----+------------+
| 1 | finished |
| 2 | finished |
| 3 | calculated |
| 4 | started |
+----+------------+
这是禁止的,因为有两种未完成状态:
+----+----------+
| id | status |
+----+----------+
| 1 | finished |
| 2 | finished |
| 3 | started |
+----+----------+
+----+------------+
| id | status |
+----+------------+
| 1 | finished |
| 2 | finished |
| 3 | calculated |
| 4 | started |
+----+------------+
您可以使用筛选唯一索引:
create unique index myindex
on mytable ((1))
where (status <> 'finished')
创建唯一索引myindex
在mytable上((1))
其中(状态为“已完成”)
诀窍是将固定值而不是列名传递给索引的on
子句(我们需要两个括号,以便Postgres将其作为表达式进行计算)。这与一个where
子句相结合,该子句过滤除“finished”之外的状态,以实现所需的逻辑