[英]Postgres unique constraint across two columns?
這是我當前的數據庫結構:
Col1 Col2
1 abc123
1 abc123
1 def321
2 xyz789
2 xyz789
我想確保Col2
中的任何條目僅用於Col1
的相同條目。 例如,數據庫將允許您添加以下行:
Col1 Col2
2 lmn456
但不是這個:
Col1 Col2
2 abc123
有沒有辦法使用唯一索引來強制執行此操作? 通常,唯一性要求特定組合對於整個表都是唯一的(即(1,abc123)
最多顯示一次)。
我無法將Col2
移動到其他表並使用Col2
,因為我需要為Col2
中的每個條目支持Col2
多個值-它不是Col1
的。
否。您的數據結構錯誤。
您應該將col2
存儲在單獨的表中,每個col1
和col2
一行。 然后,您可以使用join
查找值。
該約束將使用btree運算符<>
和=
,因此您必須安裝btree_gist擴展。
create extension if not exists btree_gist;
create table my_table(
col1 int,
col2 text,
exclude using gist (col1 with <>, col2 with =)
);
測試:
insert into my_table values
(1, 'abc123'),
(1, 'abc123'),
(1, 'def321'),
(2, 'xyz789'),
(2, 'xyz789')
returning *;
col1 | col2
------+--------
1 | abc123
1 | abc123
1 | def321
2 | xyz789
2 | xyz789
(5 rows)
insert into my_table
values (2, 'abc123');
ERROR: conflicting key value violates exclusion constraint "my_table_col1_col2_excl"
DETAIL: Key (col1, col2)=(2, abc123) conflicts with existing key (col1, col2)=(1, abc123).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.