如何在多个列之间强制执行类似集合的唯一性? [英] How do I enforce set-like uniqueness between multiple columns?
本文介绍了如何在多个列之间强制执行类似集合的唯一性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定我是否正确表达了这个问题,所以我将尝试更长的解释。我有这种表:
I'm not sure I've phrased the question correctly, so I'll try a longer explanation. I have this kind of table:
CREATE TABLE x (a int, b int);
我想将(a,b)对与(b,a)相同,并禁止插入重复项。如果PostgreSQL的数据类型为
,我可以这样声明表:
I want to consider the pair (a,b) to be identical to (b,a), and to disallow insertion of duplicates. If PostgreSQL had a set
data type, I might declare the table like this:
CREATE TABLE x (
ab set,
UNIQUE (ab)
);
但事实并非如此,那么最好的方法是什么?
But it doesn't, so what's the best way of doing this?
推荐答案
create unique index idx_unique_ab
on x (least(a,b), greatest(a,b));
这篇关于如何在多个列之间强制执行类似集合的唯一性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文