Postgresql唯一约束允许双向组合

时间:2017-10-04 17:47:11

标签: database postgresql

我在postgresql中有一个唯一的约束来加入两个表中的Id

TableA
IdA
1
2
3

TableB
IdB
1
2
3

TableJoin
IdA   IdB
1     1   --good
1     2   --good
1     3   --good

但如果我想插入另一个Id

TableJoin
IdA   IdB
1     1   --good
1     2   --good
1     3   --good
2     1   --return error, because already exist 1   2 (I need save 2   1)
2     2   --good
2     3   --good
3     1   --return error, because already exist 1   3 (I need save 3   1)

我的独特之处在于:

ALTER TABLE TableJoin ADD CONSTRAINT" UX_Join"独特(" IdA"," IdB");

如何插入两种方式(1 2 AND 2 1)?

另一个独特的变体?

Ty求助我!!!

1 个答案:

答案 0 :(得分:0)

某处已经回答了。

基本上对于整数来说,最简单的就是创建像这样的英国:

create unique index uk on tablejoin (least(ida,idb), greatest(ida,idb))

对于非整数,您可以使用索引中的顺序添加到数组和不需要。甚至另一种方式是jsonb函数我相信。但是最大/最小是两个键整数索引的最佳选择...

这是一个例子:

t=# create table a (i int, e int);
CREATE TABLE
Time: 27.528 ms
t=# create unique index u on a (i,e);
CREATE INDEX
Time: 25.309 ms
t=# insert into a select 1,2;
INSERT 0 1
Time: 13.972 ms
t=# insert into a select 2,1;
INSERT 0 1
Time: 8.759 ms
t=# select * from a;
 i | e
---+---
 1 | 2
 2 | 1
(2 rows)

Time: 14.570 ms
t=# create unique index u1 on a (least(i,e),greatest(i,e));
ERROR:  could not create unique index "u1"
DETAIL:  Key ((LEAST(i, e)), (GREATEST(i, e)))=(1, 2) is duplicated.
Time: 15.241 ms
相关问题