问题
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);
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?
回答1:
create unique index idx_unique_ab
on x (least(a,b), greatest(a,b));
回答2:
I'd just enforce that a pair can only be stored one way round then create a regular unique constraint.
CREATE TABLE x
(
a INT,
b INT,
CHECK (a < b),
UNIQUE(a, b)
);
来源:https://stackoverflow.com/questions/13430658/how-do-i-enforce-set-like-uniqueness-between-multiple-columns