Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Constraints 两列上的唯一索引,反之亦然_Constraints_Unique_Postgresql 9.5 - Fatal编程技术网

Constraints 两列上的唯一索引,反之亦然

Constraints 两列上的唯一索引,反之亦然,constraints,unique,postgresql-9.5,Constraints,Unique,Postgresql 9.5,我在postgres 9.5中有下表: CREATE TABLE public.test ( id bigint NOT NULL DEFAULT nextval('test_id_seq'::regclass), id1 integer, id2 integer, CONSTRAINT test_pkey PRIMARY KEY (id) ); 我想对这两列添加限制,这只允许记录集 新记录集(id1、id2)不存在,并且 新记录集(id1,id2)不以(id2,id1)和的形式存在 新记录集

我在postgres 9.5中有下表:

CREATE TABLE public.test
(
id bigint NOT NULL DEFAULT nextval('test_id_seq'::regclass),
id1 integer,
id2 integer,
CONSTRAINT test_pkey PRIMARY KEY (id)
);
我想对这两列添加限制,这只允许记录集

  • 新记录集(id1、id2)不存在,并且
  • 新记录集(id1,id2)不以(id2,id1)和的形式存在
  • 新记录集的id1和id2不相等
  • 应该是这样的:

     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

    最终解决方案由一匹没有名字的马帮助:

    CREATE TABLE public.test(
    id bigint NOT NULL DEFAULT nextval('test_id_seq'::regclass),
    id1 integer NOT NULL,
    id2 integer NOT NULL,
    CONSTRAINT test_pkey PRIMARY KEY (id),
    CONSTRAINT test_check CHECK (id1 <> id2)
    );
    
    CREATE UNIQUE INDEX test_id1_id2_unique
    ON public.test
    USING btree
    ((LEAST(id1, id2)), (GREATEST(id1, id2)));
    
    创建表public.test(
    id bigint NOT NULL默认值nextval('test_id_seq'::regclass),
    id1整数不为空,
    id2整数不为空,
    约束测试_pkey主键(id),
    约束测试检查(id1 id2)
    );
    创建唯一索引测试\u id1\u id2\u UNIQUE
    论公共考试
    使用btree
    ((最小的(id1,id2)),(最大的(id1,id2));
    
    您可以创建一个唯一的索引来覆盖这两个1。二,

    create unique index on test ( least(id1,id2), greatest(id1,id2) );
    
    三个人。您需要一个检查约束:

    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都
    不为NULL
    。在这种情况下,您也可以使用
    检查(id1 id2)

    感谢您将注意力集中到最小()和最大()。这些函数在PGSQL中我是未知的。
    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) 
    );