How do I enforce set-like uniqueness between multiple columns? [duplicate]

与世无争的帅哥 提交于 2019-12-02 08:33:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!