微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数组 – 数组的Postgres UNIQUE CONSTRAINT

如何创建对数组中所有值的唯一性的约束,如:
CREATE TABLE mytable
(
    interface integer[2],CONSTRAINT link_check UNIQUE (sort(interface))
)

我的排序功能

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

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

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

那么你可以这样做:

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

然后发生以下情况:

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

原文地址:https://www.jb51.cc/postgresql/191700.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐