簡體   English   中英

Postgres添加唯一約束

[英]Postgres add unique constraint

我需要向表x添加一個約束,該約束與其他表具有多對一的關系。 因此,表x具有字段other_table_id。

x還有另一列稱為primary的布爾類型。

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

多個行可以具有other_table_id等於某個相同的值,並且primary=false但每個other_table_id只有一個true

如何創建此約束?

為此,您需要一個局部唯一索引:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM