Postgres 添加唯一约束

Lon*_*don 1 sql postgresql

x我需要向与其他表具有多对一关系的表添加约束。所以该表x有字段 other_table_id。

表中还有另一列x称为primary布尔类型。

我想确保有none or only one primary=true一个other_table_id

多行可以具有other_table_id等于某个相同的值,但每行primary=false只能有一个。trueother_table_id

我如何创建这个约束?

小智 5

为此,您需要一个部分唯一索引:

create unique index idx_unique_other 
   on table_x (other_table_id)
   where primary;
Run Code Online (Sandbox Code Playgroud)

这只会索引primary列值为 的行true。对于这些,other_table_id必须是独一无二的。