Postgres:A 列、B 列的唯一约束 [值 1]
Postgres: Unique constrain on Column-A, Column-B [value1]
我有一个 table applications
,其中有 user_id
、status
等字段。 status
可能是 [0,1,2]
。
我需要施加一个约束,在应用程序 table 中,不能有多个行在 0
状态下具有相同的 user_id
。但是,在状态 1
或 2
中可能有多个行具有 user_id
。
为了演示,这是不允许的:
user_id | status
abc | 0
abc | 0
但是,这是允许的:
user_id | status
abc | 1
abc | 1
如何施加这样的约束?我正在使用 Postgres。
您可以为此使用过滤后的唯一索引:
create unique index on applications (user_id)
where status = 0;
我有一个 table applications
,其中有 user_id
、status
等字段。 status
可能是 [0,1,2]
。
我需要施加一个约束,在应用程序 table 中,不能有多个行在 0
状态下具有相同的 user_id
。但是,在状态 1
或 2
中可能有多个行具有 user_id
。
为了演示,这是不允许的:
user_id | status
abc | 0
abc | 0
但是,这是允许的:
user_id | status
abc | 1
abc | 1
如何施加这样的约束?我正在使用 Postgres。
您可以为此使用过滤后的唯一索引:
create unique index on applications (user_id)
where status = 0;