Postgres:列A,列B [value1]的唯一约束

时间:2019-11-06 09:21:42

标签: postgresql constraints unique-constraint

我有一个表applications,其中有user_idstatus和其他字段。 status可以是[0,1,2]

我需要施加一个约束,即在应用程序表中,不能有多行处于user_id状态的相同0。但是,可能会有多行状态为user_id1的{​​{1}}。

为了演示,这是不允许的:

2

但是,这是允许的:

user_id | status
abc     | 0
abc     | 0

我如何施加这样的约束?我正在使用Postgres。

1 个答案:

答案 0 :(得分:2)

您可以为此使用过滤后的唯一索引:

create unique index on applications (user_id)
where status = 0;