您可以使用排除约束,如下所示:
create table mytable (
id_a int[],
id_b int,
exclude using gist(id_a with &&, id_b with =)
);
id_a
这可以防止给定的数组重叠id_b
。
DB Fiddle 上的演示:
insert into mytable values ('{3,4,5}', 18);
-- 1 rows affected
insert into mytable values ('{3,4,5}', 18);
-- ERROR: conflicting key value violates exclusion constraint "mytable_id_a_id_b_excl"
-- DETAIL: Key (id_a, id_b)=({3,4,5}, 18) conflicts with existing key (id_a, id_b)=({3,4,5}, 18).
insert into mytable values ('{3,4,5}', 19);
-- 1 rows affected
insert into mytable values ('{3}', 19);
-- ERROR: conflicting key value violates exclusion constraint "mytable_id_a_id_b_excl"
-- DETAIL: Key (id_a, id_b)=({3}, 19) conflicts with existing key (id_a, id_b)=({3,4,5}, 19).
insert into mytable values ('{6}', 18);
-- 1 rows affected