我需要向表x
添加一个约束,该表与其他表有多对一的关系。因此,表x
具有字段other_table_id。
表x
中还有一个名为primary
的列,它是布尔类型。
我想确保每none or only one primary=true
个other_table_id
。
多行可以other_table_id
等于某个相同的值primary=false
,但每true
只有一个other_table_id
。
如何创建此约束?
答案 0 :(得分:4)
您需要一个部分唯一索引:
create unique index idx_unique_other
on table_x (other_table_id)
where primary;
这只会将primary
列的值为true
的行编入索引。对于那些人来说,other_table_id
必须是唯一的。