2017-05-31 110 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