2013-11-01 161 views
0

我需要添加約束到表x,它與其他表具有多對一的關係。所以表x有字段other_table_id。Postgres添加唯一約束

x中還有一列叫做primary,它是布爾類型。

我想確保每個other_table_idnone or only one primary=true

多行可以有other_table_id等於一些相同的價值和primary=false但每other_table_id只有一個true

如何創建此約束?

回答

4

您需要爲該部分唯一索引:

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

這隻會索引行primary列的值是true。對於那些,other_table_id必須是唯一的。