数组 – 数组的Postgres UNIQUE CONSTRAINT

前端之家收集整理的这篇文章主要介绍了数组 – 数组的Postgres UNIQUE CONSTRAINT前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何创建对数组中所有值的唯一性的约束,如:
  1. CREATE TABLE mytable
  2. (
  3. interface integer[2],CONSTRAINT link_check UNIQUE (sort(interface))
  4. )

我的排序功能

  1. create or replace function sort(anyarray)
  2. returns anyarray as $$
  3. select array(select $1[i] from generate_series(array_lower($1,1),array_upper($1,1)) g(i) order by 1)
  4. $$language sql strict immutable;

我需要这样的价值{10,22}和{22,10}被认为是一样的,并在独特的约束下检查

我不认为你可以使用一个 unique constraint功能,但你可以使用 unique index.所以给出一个这样的排序功能
  1. create function sort_array(integer[]) returns integer[] as $$
  2. select array_agg(n) from (select n from unnest($1) as t(n) order by n) as a;
  3. $$language sql immutable;

那么你可以这样做:

  1. create table mytable (
  2. interface integer[2]
  3. );
  4. create unique index mytable_uniq on mytable (sort_array(interface));

然后发生以下情况:

  1. => insert into mytable (interface) values (array[11,23]);
  2. INSERT 0 1
  3. => insert into mytable (interface) values (array[11,23]);
  4. ERROR: duplicate key value violates unique constraint "mytable_uniq"
  5. DETAIL: Key (sort_array(interface))=({11,23}) already exists.
  6. => insert into mytable (interface) values (array[23,11]);
  7. ERROR: duplicate key value violates unique constraint "mytable_uniq"
  8. DETAIL: Key (sort_array(interface))=({11,23}) already exists.
  9. => insert into mytable (interface) values (array[42,11]);
  10. INSERT 0 1

猜你在找的Postgre SQL相关文章