我基本上想做的是模仿 array_cat postgres 表中的功能,但改为减去数组。
有一个功能array_remove但它一次只删除一个元素。
我无法弄清楚如何在单个查询中实现这一点,我不想使用循环。任何帮助,将不胜感激。
array_remomany(ARRAY{1,2,3,4}, {1,2}) 应该给出结果 {3,4}
最佳答案
它不使用循环而是使用查询:
select array_agg(x)
from unnest('{1,3,2,4}'::numeric[]) as x
where x not in (1,2)
-- or x <> all('{1,2}'::numeric[])
;
┌───────────┐
│ array_agg │
├───────────┤
│ {3,4} │
└───────────┘
您可以将此查询包装到函数中:create function array_remove_many(anyarray, anyarray)
returns anyarray
language sql
immutable
as $$
select array_agg(x) from unnest($1) as x where x <> all($2)
$$;
select array_remove_many(array[1,3,2,4], array[1,2]);
┌───────────────────┐
│ array_remove_many │
├───────────────────┤
│ {3,4} │
└───────────────────┘
您可以将它用于任何数组类型。
关于arrays - 在不使用循环的情况下从 Postgresql 数组中减去一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64651078/