如何将数组项插入PostgreSQL表

如何将数组项插入PostgreSQL表,sql,arrays,postgresql,Sql,Arrays,Postgresql,给出如下数组: my_array = [2,3,5,23,4] 还有一张这样的桌子: column1 | column2 ---------+---------- 1 | 2 | 3 | 4 | 5 | with numbered_data as ( select ctid, row_number() over (order by column1) as

给出如下数组:

my_array = [2,3,5,23,4]
还有一张这样的桌子:

 column1 | column2 
---------+----------
   1     |     
   2     |     
   3     |     
   4     |     
   5     | 
with numbered_data as (
  select ctid,
         row_number() over (order by column1) as rn --<< this generates the array index values 
  from test         
)
update test  
  set column2  = (array[2,3,5,23,4])[nd.rn]
from numbered_data nd
where nd.ctid = test.ctid;
如何将数组值插入表中。大致上,我想用SQL执行以下操作:

for item in my_array:
 UPDATE my_table SET colum2 = item
更新后的表应该是这样的

 column1 | column2 
---------+----------
   1     |     2 
   2     |     3 
   3     |     5 
   4     |     23 
   5     |     4 
更新: 我正在使用Python psycopg2,但我想知道是否有一种方法可以使用纯SQL。

像这样

 column1 | column2 
---------+----------
   1     |     2 
   2     |     3 
   3     |     5 
   4     |     23 
   5     |     4 
insert into my_table( ..., my_column, ... )
select ..., item, ...
from   dual, ...
where item in (<your array> )
插入my_表(…,my_列…)
选择…,项目。。。
从双。。。
其中项目位于()

您需要以某种方式为表中的每一行生成一个数组“索引”

如果
列1
始终与数组索引匹配,则可以这样做

update test  
  set column2 = (array[2,3,5,23,4])[column1];
但是,如果
column1
中的值不反映数组索引,则需要根据表中的排序顺序生成数组索引。如果是这种情况,您可以这样做:

 column1 | column2 
---------+----------
   1     |     
   2     |     
   3     |     
   4     |     
   5     | 
with numbered_data as (
  select ctid,
         row_number() over (order by column1) as rn --<< this generates the array index values 
  from test         
)
update test  
  set column2  = (array[2,3,5,23,4])[nd.rn]
from numbered_data nd
where nd.ctid = test.ctid;
将编号的_数据作为(
选择ctid,

在Postgres 9.4中,将(按列1排序)上的行数()作为rn--使用带有顺序性的
。比任何其他方法都更快、更干净

UPDATE test t
SET    column2 = a.column2
FROM   unnest('{2,3,5,23,4}'::int[]) WITH ORDINALITY a(column2, column1)
WHERE  t.column1 = a.column1;
假设
column1
表示
column2
在给定数组中的位置,这只会更新应该更新的列,而不会触及其他行(就像@a_horse的答案中的简单查询一样)

元素的序号位置也是一维数组中的默认数组下标,但Postgres允许任意数组索引:


这与实际的数组下标无关。

是否要在一列、单独的列或单独的行中添加整个数组元素?您使用的是哪种编程语言?您是如何在语言中定义该数组的?如果数组中的元素多于或少于表中的行,该怎么办?元素索引位置是否为always等于
第1列中的值(请记住:关系表中的行未排序,因此不能按“位置”将数组元素映射到表行)我正在将Python与psycopg2一起使用,但我想知道是否可以使用纯SQL。数组中的元素数量始终与表中的行数量相同。我将使用where语句确保将正确的数组值映射到正确的行。
column1
中的值真的应该是数组索引中的值吗?或者这只是一个误读举个例子?和往常一样,你的Postgres版本是相关的。
dual
在Postgres中没有特别的意义。这甚至不接近于答案。你能逐字解释一下
set column2=(array[foo])[bar]
的右边吗?