【发布时间】: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。
【问题讨论】: