简体   繁体   English

Postgres将数组的每个元素(如果不存在)追加或设置为数组列

[英]Postgres append or set each elements(if not exists) of an array to an array column

If I have 如果我有

select arr_str from tabl1;
-> {'a', 'b'}

then how do I add this {'b','c','d'} array to column arr_str so that I would get the following result 那么如何将这个{'b','c','d'}数组添加到列arr_str以便我得到以下结果

select arr_str from tabl1;
-> {'a', 'b', 'c', 'd'}

I don't want to SELECT the column and create a new array for updating. 我不想选择列并创建一个新数组进行更新。 I only want to use UPDATE query. 我只想使用UPDATE查询。

I'll assume that arr_str is of type text[] (although you did not use the proper format for them, so I may be wrong; if that's the case, you'll need to cast your value to text[] ). 我假设arr_str的类型是text[] (虽然你没有使用正确的格式,所以我可能是错的;如果是这种情况,你需要将你的值转换为text[] )。

Use the following statement, if you want to remove duplications, which are already present in the arr_str column: 如果要删除arr_str列中已存在的重复项,请使用以下语句:

update tabl1
set    arr_str = (select array_agg(distinct e) from unnest(arr_str || '{b,c,d}') e)
where  not arr_str @> '{b,c,d}'

Or, use the following one when you want to preserve existing duplications: 或者,如果要保留现有重复项,请使用以下内容:

update tabl1
set    arr_str = arr_str || array(select unnest('{b,c,d}'::text[]) except select unnest(arr_str))
where  not arr_str @> '{b,c,d}'

Both of these statements won't touch rows, which won't be affected anyway (look at the where not arr_str @> '{b,c,d}' predicate). 这两个语句都不会触及行,这些行不会受到任何影响(请查看where not arr_str @> '{b,c,d}'谓词)。 This is usualy the best practice, and is almost always recommended, when triggers are involved. 这通常是最佳实践,并且在涉及触发器时几乎总是被推荐。

http://rextester.com/GKS7382 http://rextester.com/GKS7382

With default pg install you can merge two arrays with || 使用默认的pg install,您可以使用||合并两个数组 operator: 运营商:

select arr_str || '{a, b}' from tabl1

But in that case you will get duplicates. 但在这种情况下,你会得到重复。

To avoid them, you can unnest array into rowset and distinct it: 为了避免它们,你可以将数组替换为rowset并将其区分开来:

select ARRAY(SELECT DISTINCT UNNEST(arr_str || '{a,b,c}')) from tabl1

If your values are integers, there is more elegant way to get uniq array values with intarray contrib module and uniq() function: https://www.postgresql.org/docs/current/static/intarray.html 如果你的值是整数,那么使用intarray contrib模块和uniq()函数获得uniq数组值有更优雅的方法: https ://www.postgresql.org/docs/current/static/intarray.html

You can add these integer array functions by using: 您可以使用以下命令添加这些整数数组函数:

CREATE EXTENSION intarray

you can concatenate arrays and then aggregate distinct values: 您可以连接数组,然后聚合不同的值:

t=# with a as (select unnest('{a, b}'::text[] || '{b,c,d}'::text[]) a) select array_agg(distinct a) from a;
 array_agg
-----------
 {a,b,c,d}
(1 row)

Time: 1.312 ms

试试这段代码:

select array(select distinct unnest(string_to_array('a,b',',') || string_to_array('b,c,d',',')) order by 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM