我有一张类似的表:
CREATE TABLE members (
member_id SERIAL PRIMARY KEY,
email text,
archived boolean DEFAULT FALSE,
CONSTRAINT members_email_key UNIQUE(email)
);
我需要unique-constraint才能仅考虑活动成员(注释存档:archived=False
)。所以以下内容是有效的:
insert into members(name, email) values('ulf','ulf@example.com');
insert into members(name, email) values('foo','foo@example.com');
insert into members(name, email) values('baz','baz@example.com');
update members set archived = True where name = 'ulf';
insert into members(name, email) values('Newulf','ulf@example.com');
但这应该失败:
insert into members(name, email) values('foo','foo@example.com');
insert into members(name, email) values('Anotherfoo','foo@example.com');
所以我知道我需要删除现有的约束:
ALTER TABLE members DROP CONSTRAINT members_email_key;
但是如何创建一个符合我想要的新约束呢?我一直在关注EXCLUDE
- clous,但不完全了解如何应用它。我尝试了一些变化而没有成功:
ALTER TABLE members ADD CONSTRAINT email_for_valid_members EXCLUDE USING gist (email with =, ...
有关EXCLUDE
的文档:
我正在使用postgresql 9.6。
答案 0 :(得分:2)
创建部分唯一索引:
create unique index only_one_active_email
on members(email)
where not archived;