是否可以对所有行的子集设置唯一约束?
Is it possible to set unique constraint to the subset of all rows?
我在 PostgreSQL 9.4
。我有以下 table:
id name deleted
seril PK varchar(32) boolean NOT NULL
是否可以将 UNIQUE
约束应用于具有 deleted = false
的所有行?
您可以使用部分索引来完成。
来自文档
When the WHERE clause is present, a partial index is created. A partial index is an index that contains entries for only a portion of a table, usually a portion that is more useful for indexing than the rest of the table. For example, if you have a table that contains both billed and unbilled orders where the unbilled orders take up a small fraction of the total table and yet that is an often used section, you can improve performance by creating an index on just that portion. Another possible application is to use WHERE with UNIQUE to enforce uniqueness over a subset of a table. See Section 11.8 for more discussion.
参考:http://www.postgresql.org/docs/9.4/static/sql-createindex.html
再举个例子:
CREATE UNIQUE INDEX yourindexname onyourtable (seril)
WHERE deleted = false;
自 Postgresql 7.2 版本起支持此功能。
我在 PostgreSQL 9.4
。我有以下 table:
id name deleted
seril PK varchar(32) boolean NOT NULL
是否可以将 UNIQUE
约束应用于具有 deleted = false
的所有行?
您可以使用部分索引来完成。
来自文档
When the WHERE clause is present, a partial index is created. A partial index is an index that contains entries for only a portion of a table, usually a portion that is more useful for indexing than the rest of the table. For example, if you have a table that contains both billed and unbilled orders where the unbilled orders take up a small fraction of the total table and yet that is an often used section, you can improve performance by creating an index on just that portion. Another possible application is to use WHERE with UNIQUE to enforce uniqueness over a subset of a table. See Section 11.8 for more discussion.
参考:http://www.postgresql.org/docs/9.4/static/sql-createindex.html
再举个例子:
CREATE UNIQUE INDEX yourindexname onyourtable (seril)
WHERE deleted = false;
自 Postgresql 7.2 版本起支持此功能。