【问题标题】:postgresql unique constraint for any integer from two columns (or from array)来自两列(或来自数组)的任何整数的postgresql唯一约束
【发布时间】:2016-12-02 23:09:58
【问题描述】:

如何保证两列/数组中任意个整数的唯一性?

示例:我创建一个表并在其中插入一行:

CREATE TABLE mytest(a integer NOT NULL, b integer NOT NULL);
INSERT INTO mytest values (1,2);

我应该创建什么 UNIQUE INDEX 以不允许添加以下任何值

INSERT INTO mytest values (1,3); # because 1 is already there
INSERT INTO mytest values (3,1); # because 1 is already there
INSERT INTO mytest values (2,3); # because 2 is already there
INSERT INTO mytest values (3,2); # because 2 is already there

如果有帮助的话,我可以有两个元素的数组而不是两列。

当然,我可以发明一些解决方法,我想到了以下方法:

  • 为所有数字创建单独的表,在那里有unique index,并将值添加到两个带有事务的表中。如果编号不唯一,则不会加入第二张表,交易失败
  • 添加两行而不是一行,并为id-of-the-pair 增加一个字段。

但我想要一张桌子,我需要一排有两个元素。这可能吗?

【问题讨论】:

  • 一个唯一的索引/约束在这里是不够的,但你可以用an exclusion constraint做一些事情。我已经看到它们被描述为一种“超级通用的唯一约束”,但从未实际使用过,而且手册似乎对示例很简单。

标签: postgresql


【解决方案1】:

您可以在 table 上使用排除约束以及 intarray 来快速执行重叠数组的搜索:

CREATE EXTENSION intarray;
CREATE TABLE test (
    a int[],
    EXCLUDE USING gist (a gist__int_ops WITH &&)
);

INSERT INTO test values('{1,2}');

INSERT INTO test values('{2,3}');
>> ERROR:  conflicting key value violates exclusion constraint "test_a_excl"
>> DETAIL:  Key (a)=({2,3}) conflicts with existing key (a)=({1,2}).

【讨论】:

  • 您不需要将其作为数组存储在表中。 EXCLUDE USING gist ((array[a,b]) WITH &&) 也可以使用
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 2023-01-25
  • 1970-01-01
相关资源
最近更新 更多