postgresql 如何删除PostgreSQL中的数组元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37917905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove elements of array in PostgreSQL?
提问by k.xf
Is it possible to remove multipleelements from an array? Before removing elements Array1 is :
是否可以从数组中删除多个元素?在删除元素之前 Array1 是:
{1,2,3,4}
Array2 that contains some elements I wish to remove:
Array2 包含一些我希望删除的元素:
{1,4}
And I want to get:
我想得到:
{2,3}
How to operate?
如何操作?
回答by klin
Use unnest()
with array_agg()
, e.g.:
unnest()
与 一起使用array_agg()
,例如:
with cte(array1, array2) as (
values (array[1,2,3,4], array[1,4])
)
select array_agg(elem)
from cte, unnest(array1) elem
where elem <> all(array2);
array_agg
-----------
{2,3}
(1 row)
If you often need this functionality, define the simple function:
如果您经常需要此功能,请定义简单函数:
create or replace function array_diff(array1 anyarray, array2 anyarray)
returns anyarray language sql immutable as $$
select coalesce(array_agg(elem), '{}')
from unnest(array1) elem
where elem <> all(array2)
$$;
You can use the function for any array, not only int[]
:
您可以将该函数用于任何数组,不仅是int[]
:
select array_diff(array['a','b','c','d'], array['a','d']);
array_diff
------------
{b,c}
(1 row)
回答by Denys Séguret
With the intarray extension, you can simply use -
:
使用 intarray 扩展,您可以简单地使用-
:
select '{1,2,3,4}'::int[] - '{1,4}'::int[]
Result:
结果:
{2,3}
You'll need to installthe intarray extension if you didn't already. It adds many convenient functions and operators if you're dealing with arrays of integers.