【问题标题】:Unique constraint on two columns irrespective of order [duplicate]无论顺序如何,两列的唯一约束[重复]
【发布时间】:2020-02-26 06:20:18
【问题描述】:

我有一个非常简单的表格:

    id  | name   | alternate
--------+--------+------------
     1  |   Joe  |     Joseph
--------+--------+------------
     2  |   Pete |     Peter
--------+--------+------------

等等。

我想在名称和备用列上添加一个约束,但不考虑顺序。例如,我不想插入(3, 'Peter', 'Pete'),因为这与 id 2 基本相同,只是列颠倒了。

有没有办法做到这一点?

【问题讨论】:

    标签: sql postgresql create-table unique-constraint


    【解决方案1】:

    创建唯一索引:

    CREATE UNIQUE INDEX ON atable
       (LEAST(name, alternate), GREATEST(name, alternate));
    

    【讨论】:

      【解决方案2】:

      您可以创建唯一索引:

      create unique index my_unique_idx
      on mytable(least(name, alternate), greatest(name, alternate));
      

      Demo on DB Fiddle

      create table mytable (name varchar(10), alternate varchar(10));
      
      create unique index my_unique_idx
      on mytable(least(name, alternate), greatest(name, alternate));
      
      insert into mytable values('foo', 'bar');
      -- 1 rows affected
      
      insert into mytable values('bar', 'foo')
      -- ERROR:  duplicate key value violates unique constraint "my_unique_idx"
      -- DETAIL:  Key (LEAST(name, alternate), GREATEST(name, alternate))=(bar, foo) already exists.
      

      【讨论】:

        猜你喜欢
        • 2012-07-10
        • 2017-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多