postgresql 向 Postgres 整数数组添加值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40640015/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:26:42  来源:igfitidea点击:

Adding value to Postgres integer array

arrayspostgresqlpostgresql-9.5

提问by Kyle K

I am looking for help in adding a value 10to an int[]in PostgreSQL 9.5.

我正在寻求帮助以向PostgreSQL 9.5 中的10an添加值int[]

Looking at the documentation I should be able to use this format to update it but it is not working:

查看文档我应该能够使用这种格式来更新它,但它不起作用:

int[] + int   push element onto array (add it to end of array)

I have tried running this:

我试过运行这个:

update table1 set integer_array = integer_array + 10::Integer. 

It did not work and I got this error:

它没有用,我收到了这个错误:

ERROR: operator does not exist: integer[] + integer
  Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
  Position: 67

I feel this is the same format like the one presented in the documentation on how to perform this operation.

我觉得这与有关如何执行此操作的文档中提供的格式相同。

回答by Kamil Gosciminski

Use array_appendfunction to append an element at the end of an array:

使用array_append函数在数组末尾追加一个元素:

UPDATE table1
SET integer_array = array_append(integer_array, 5);

5 is a value of choice, it's of an integer datatype in your case. You probably need some WHEREclause as well not to update the entire table.

5 是一个选择值,在您的情况下它是整数数据类型。您可能还需要一些WHERE子句来不更新整个表。

Try below to see how it works:

试试下面的方法看看它是如何工作的:

SELECT ARRAY[1,2], array_append(ARRAY[1,2],3);

Result:

结果:

 array | array_append
-------+--------------
 {1,2} | {1,2,3}

回答by Marat Safin

I like this way better:

我更喜欢这种方式:

UPDATE table1 SET integer_array = integer_array || '{10}';

You can also add multiple values with single query:

您还可以使用单个查询添加多个值:

UPDATE table1 SET integer_array = integer_array || '{10, 11, 12}';

回答by Fernando Meneses Gomes

-- Declaring the array

arrayName int8[];

-- Adding value 2206 to int array

arrayName := arrayName || 2206;

-- looping throught the array

FOREACH i IN ARRAY arrayName 
LOOP 

 RAISE NOTICE 'array value %', i;

END LOOP;

cheers

干杯