【问题标题】:Place complex uniqueness constraint in Postgres?在 Postgres 中放置复杂的唯一性约束?
【发布时间】:2017-10-07 18:45:15
【问题描述】:

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

【问题讨论】:

    标签: postgresql constraints


    【解决方案1】:

    使用部分或过滤索引:

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

    这在部分索引部分的documentation 中有描述。

    【讨论】:

      猜你喜欢
      • 2011-11-12
      • 1970-01-01
      • 2014-06-20
      • 2015-03-06
      • 2013-05-25
      • 2022-08-22
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多