在Postgres中放置复杂唯一性约束?

时间:2017-10-07 18:45:15

标签: postgresql constraints

Postgres中,我有一个包含三列的表user_badge,显示如下:

# select * from user_badge;
 id | user_id | badge_id | is_active |
----+---------+----------+------------
 1    bob       00001      False
 2    bob       00002      True
 3    alice     00003      True
 4    alice     00004      False
 5    alice     00005      False

在此表中,用户可以拥有多个徽章,但每个用户不得拥有多个活动徽章(即is_active列为True的行。)

另一种说法是,查询

SELECT user_id FROM user_badge WHERE is_active;

必须返回唯一的行。

这是我希望放在此表上的约束。 有没有办法指定Postgres来保证它?在Postgres的documentation on constraints中我看到如何才能在列和集合上放置唯一性约束列,但没有看到唯一性约束涉及WHERE的示例。

1 个答案:

答案 0 :(得分:5)

使用部分或过滤索引:

create unique index unq_user_badge_user_is_active
    on user_badge(user) where is_active;

有关部分索引的部分documentation中对此进行了描述。