我有一个表applications
,其中有user_id
,status
和其他字段。 status
可以是[0,1,2]
。
我需要施加一个约束,即在应用程序表中,不能有多行处于user_id
状态的相同0
。但是,可能会有多行状态为user_id
或1
的{{1}}。
为了演示,这是不允许的:
2
但是,这是允许的:
user_id | status
abc | 0
abc | 0
我如何施加这样的约束?我正在使用Postgres。
答案 0 :(得分:2)
您可以为此使用过滤后的唯一索引:
create unique index on applications (user_id)
where status = 0;