Postgres添加了唯一约束

时间:2013-11-01 09:49:10

标签: sql postgresql

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

x中还有一个名为primary的列,它是布尔类型。

我想确保每none or only one primary=trueother_table_id

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

如何创建此约束?

1 个答案:

答案 0 :(得分:4)

您需要一个部分唯一索引:

create unique index idx_unique_other 
   on table_x (other_table_id)
   where primary;

这只会将primary列的值为true的行编入索引。对于那些人来说,other_table_id必须是唯一的。