[英]How to insert array items into PostgreSQL table
Give an array like this: 给这样一个数组:
my_array = [2,3,5,23,4]
and a table like this: 和这样的表格:
column1 | column2
---------+----------
1 |
2 |
3 |
4 |
5 |
How can I insert the array values into a table. 如何将数组值插入表中。 Roughly I want to do something like this with SQL:
粗略地我想用SQL做这样的事情:
for item in my_array:
UPDATE my_table SET colum2 = item
The updated table should be like this 更新的表应该是这样的
column1 | column2
---------+----------
1 | 2
2 | 3
3 | 5
4 | 23
5 | 4
UPDATE: I am using Python psycopg2 but I am wondering if there is a way with pure SQL. 更新:我正在使用Python psycopg2,但我想知道是否有一种方法与纯SQL。
In Postgres 9.4 use the WITH ORDINALITY
for this. 在Postgres 9.4中使用
WITH ORDINALITY
。 Faster and cleaner than anything else. 比其他任何东西都更快更干净。
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;
Assuming that column1
represents the position of column2
in the given array, this only updates columns that are supposed to be updated and does not touch other rows (like the simple query in @a_horse's answer would). 假设
column1
表示给定数组中column2
的位置,这只会更新应该更新的列而不会触及其他行(就像@a_horse的答案中的简单查询一样)。
The ordinal position of an element is also the default array subscript in a 1-dimensional array, but Postgres allows arbitrary array indices: 元素的序数位置也是一维数组中的默认数组下标,但Postgres允许任意数组索引:
This works irregardless of actual array subscripts. 无论实际的数组下标如何,这都是有效的。
You need to somehow generate an array "index" for each row in the table. 您需要以某种方式为表中的每一行生成一个数组“索引”。
If the column1
value always matches the array index, you can do it like this. 如果
column1
值始终与数组索引匹配,则可以这样做。
update test
set column2 = (array[2,3,5,23,4])[column1];
However if the value in column1
does not reflect the array index, you need to generate the array index based on the sort order in the table. 但是,如果
column1
中的值不反映数组索引,则需要根据表中的排序顺序生成数组索引。 If that is the case you can do something like this: 如果是这种情况,你可以这样做:
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;
If your table has a proper primary key, then you can use that instead of the ctid
column. 如果您的表具有正确的主键,则可以使用该键而不是
ctid
列。
like this 像这样
insert into my_table( ..., my_column, ... )
select ..., item, ...
from dual, ...
where item in (<your array> )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.