简体   繁体   English

Postgresql:有条件的唯一约束

[英]Postgresql: Conditionally unique constraint

I'd like to add a constraint which enforces uniqueness on a column only in a portion of a table.我想添加一个约束,该约束仅对表的一部分中的列强制执行唯一性。

ALTER TABLE stop ADD CONSTRAINT myc UNIQUE (col_a) WHERE (col_b is null);

The WHERE part above is wishful thinking.上面的WHERE部分是一厢情愿的想法。

Any way of doing this?有没有办法做到这一点? Or should I go back to the relational drawing board?还是我应该回到关系绘图板?

PostgreSQL doesn't define a partial (ie conditional) UNIQUE constraint - however, you can create a partial unique index . PostgreSQL 没有定义部分(即条件) UNIQUE约束——但是,您可以创建部分唯一索引 PostgreSQL uses unique indexes to implement unique constraints, so the effect is the same, you just won't see the constraint listed in information_schema . PostgreSQL 使用唯一索引来实现唯一约束,所以效果是一样的,你只是不会看到information_schema列出的约束。

CREATE UNIQUE INDEX stop_myc ON stop (col_a) WHERE (col_b is NOT null);

See partial indexes .请参阅部分索引

it has already been said that PG doesn't define a partial (ie conditional) UNIQUE constraint.已经说过 PG 没有定义部分(即有条件的)UNIQUE 约束。 Also documentation says that the preferred way to add a unique constraint to a table is ADD CONSTRAINT Unique Indexes还文档说向表添加唯一约束的首选方法是ADD CONSTRAINT Unique Indexes

The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT.向表添加唯一约束的首选方法是 ALTER TABLE ... ADD CONSTRAINT。 The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly.使用索引来强制唯一约束可以被视为不应直接访问的实现细节。 One should, however, be aware that there's no need to manually create indexes on unique columns;但是,应该注意没有必要在唯一的列上手动创建索引; doing so would just duplicate the automatically-created index.这样做只会复制自动创建的索引。

There is a way to implement it using Exclusion Constraints , (thank @dukelion for this solution)有一种方法可以使用Exclusion Constraints来实现它,(感谢 @dukelion 提供此解决方案)

In your case it will look like在你的情况下,它看起来像

ALTER TABLE stop ADD CONSTRAINT myc EXCLUDE (col_a WITH =) WHERE (col_b IS null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM