简体   繁体   English

允许两种方式组合的 Postgresql 唯一约束

[英]Postgresql unique constraint to allow two way combination

I have a unique constraint in postgresql to join the Id's from two tables我在 postgresql 中有一个独特的约束来连接两个表中的 Id

TableA
IdA
1
2
3

TableB
IdB
1
2
3

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

But if I want to Insert the another Id's但是如果我想插入另一个 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)

My unique is:我的独特之处在于:

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

How can I insert two ways (1 2 AND 2 1) ?如何插入两种方式(1 2 AND 2 1)?

Another alter unique?另一个改变独特?

Ty for help me !!!泰帮助我!!!

It was answered somewhere.它在某处得到了回答。

basically for integers, the easiest would be creating a UK like this:基本上对于整数,最简单的方法是创建一个像这样的英国:

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

for not integers you can add to array and unnest with order in index.对于非整数,您可以添加到数组并按索引顺序取消嵌套。 and even another way was with jsonb functions I believe.甚至另一种方式是使用 jsonb 函数,我相信。 But greatest/least is the best option for two keys integer index...但是最大/最小是两个键整数索引的最佳选择......

here's a example:这是一个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM