两列唯一索引,反之亦然

时间:2018-05-18 06:22:23

标签: constraints unique postgresql-9.5

我在postgres 9.5中有下表:

order

我想在两个列上添加限制,只允许记录集

  1. 新记录集(id1,id2)不存在且
  2. 新记录集(id1,id2)不存在为(id2,id1)和
  3. 新记录集的id1和id2不相等
  4. 它应该像这样:

    CREATE TABLE public.test
    (
    id bigint NOT NULL DEFAULT nextval('test_id_seq'::regclass),
    id1 integer,
    id2 integer,
    CONSTRAINT test_pkey PRIMARY KEY (id)
    );
    

    对于限制1,我添加了:

     id | id1 | id2
    ---------------
     1  | 1   | 1    <-- invalid (violates restriction 3.)
     2  | 1   | 2    <-- valid
     3  | 1   | 2    <-- invalid (violates restriction 1.)
     4  | 2   | 1    <-- invalid (violates restriction 2.)
     5  | 3   | 1    <-- valid
     6  | 3   | 2    <-- valid
    

    但是如何为2.和3添加约束。?

    在a_horse_with_no_name:

    的帮助下的最终解决方案
    ALTER TABLE test ADD CONSTRAINT test_id1_id2_unique UNIQUE(id1, id2);
    

1 个答案:

答案 0 :(得分:0)

您可以创建一个唯一索引来涵盖1.和2.

create unique index on test ( least(id1,id2), greatest(id1,id2) );

对于3.您需要检查约束:

CREATE TABLE public.test
(
  id bigint NOT NULL DEFAULT nextval('test_id_seq'::regclass),
  id1 integer,
  id2 integer,
  constraint check_not_equal check (id1 is distinct from id2),
  CONSTRAINT test_pkey PRIMARY KEY (id) 
);

您可能希望两个ID都为NOT NULL。在这种情况下,您还可以使用check (id1 <> id2)

相关问题