简体   繁体   English

PostgreSQL:如何将数组中的值插入表中

[英]PostgreSQL:How to insert values in an array into a table

for example, 例如,

myelems is my table 骨髓是我的餐桌

create table myelems (id int,element text)

and if I have an array 如果我有一个数组

ARRAY['A','B','C']

then how to insert the values in the above array into my table myelems ? 然后如何将上述数组中插入到我的表骨髓中
ie,

 id|element 
---+-------
 1 |A
 2 |B
 3 |C

Try like this 这样尝试

insert into myelems select row_number() OVER () AS rn,* from 
(select unnest(Array['A','B','C'])) as t

Assuming that ID by default is generated from a sequence, you can use: 假设默认情况下,ID是从序列中生成的,则可以使用:

INSERT INTO myelms(myelms) 
SELECT UNNEST(ARRAY['A','B','C'])

However if you don't have a sequence and need to specify an id, you can use two unnest to insert your data. 但是,如果您没有序列并且需要指定ID,则可以使用两个嵌套嵌套来插入数据。

INSERT INTO myelms(id,myelms)
SELECT UNNEST(ARRAY[1,2,3]),UNNEST(ARRAY['A','B','C'])

using the second option requires you to have the same number of elements in both unnest or else you will get the Cartesian product of both which will result in data that you do not want. 使用第二个选项要求您在两个嵌套中都具有相同数量的元素,否则您将获得两者的笛卡尔积,这将导致生成您不想要的数据。 And of course you need to make sure the ID is not in there already. 当然,您需要确保ID不在其中。

IDs should generally be generated from sequence since having to create your own ID can cause problems and duplicates. 通常必须从序列中生成ID,因为必须创建自己的ID可能会导致问题和重复。 Since there are no other columns beside elements, I will assume that ID is your primary key, and all keys need to be unique. 由于元素旁边没有其他列,因此我假设ID是您的主键,并且所有键都必须是唯一的。

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

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