2017-05-31 102 views
0

我有兩列,id1和id2表。PostgreSQL連接約束

如果我在例如foo-bar分別在這些列中,我需要一個禁止進入bar-foo的約束。

謝謝!

+0

您運行的是什麼版本.. –

+0

我爲使用PostgreSQL 9.6.2 – zlaayaa

回答

1
CREATE TABLE mytable(
    id1 integer, 
    id2 integer 
); 

CREATE UNIQUE INDEX ON mytable(least(id1, id2), greatest(id1, id2)); 

這應該DDO的伎倆:

test=> INSERT INTO mytable VALUES (1, 2); 
INSERT 0 1 
test=> INSERT INTO mytable VALUES (1, 3); 
INSERT 0 1 
test=> INSERT INTO mytable VALUES (2, 1); 
ERROR: duplicate key value violates unique constraint "mytable_least_greatest_idx" 
DETAIL: Key ((LEAST(id1, id2)), (GREATEST(id1, id2)))=(1, 2) already exists. 
+0

感謝,它的文字工作太! – zlaayaa

+0

它可以處理任何可排序的類型。 – klin