postgresql - Postgres : Unique constrain on Column-A, Column-B [value1]

标签 postgresql constraints unique-constraint

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

我需要在 applications 表中施加一个约束,在 0 状态下不能有多个具有相同 user_id 的行。然而,在状态 12 中可能有多个具有 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;

关于postgresql - Postgres : Unique constrain on Column-A, Column-B [value1],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58726768/

相关文章:

mysql - 如何将数组插入数据库表?

SQL/Oracle : Is it possible to have a group function in a check constraint?

MySQL 唯一和 NULL 索引建议

postgresql - 为什么我不能在 PostgreSQL 中设置这个唯一约束?

php - 无法使用 brew 找到 PHP 的 php72-pdo-pgsql/PostgreSQL 驱动程序

java - 如何在 Java 中将多对多关系建模为类?

postgresql - postgres中用逗号分割字符串

ios - Swift:动画后将 UIView 的框架重置为其约束

ios - swift ios 通过循环为多个 subview 添加约束

python - Django 唯一约束