如何一次将多个值插入Postgres表中?


93

我有一个表,我试图一次更新多个值。这是表模式:

    Column     |  Type   | Modifiers 
---------------+---------+-----------
 user_id       | integer | 
 subservice_id | integer |

我有user_id,想要subservice_id一次插入多个。有没有一种语法Postgres可以让我做这样的事情

insert into user_subservices(user_id, subservice_id) values(1, [1, 2, 3]);

我该怎么做?


1
如果你想从一个序列,或使用插入它们generate_series看到dba.stackexchange.com/a/89544/16892
rogerdpack

Answers:


59

尝试:

INSERT INTO user_subservices(user_id, subservice_id) 
SELECT 1 id, x
FROM    unnest(ARRAY[1,2,3,4,5,6,7,8,22,33]) x

演示:http ://www.sqlfiddle.com/#!15/ 9a006/1


172

多值插入语法为:

insert into table values (1,1), (1,2), (1,3), (2,1);

但是克罗科迪尔科的答案很不客气。


使用这些方法中的任何一种,是否有方法也可以返回id
dvtan

2
是的,请使用退货。“将返回id的表(id,yada)值(1,2),(9,22)插入;” 等
Scott Marlowe

1
如今,CTE又称为WITH语句通常效果很好。
Scott Marlowe

整数值可以像上面一样插入。但是在使用上述方法插入文本时,不存在像列这样的获取错误。insert into orders_cancel_reasons_infos values (1,1,"Changed my mind",1), (2,2,"Quality not satisfactory",1), (3,3,"Incompatible or not useful",1), (4,4,"Damaged product but shipping box is good",1), (5,5,"Items arrived too late",1), (6,6,"Missing part or accessories",1), (7,7,"Product and shipping box are damaged",1), (8,8,"Wrong item was sent",1), (9,9,"Defective item",1), (10,10,"Inaccurate description",1), (11,11,"Other",1);
sankar muniyappa '18

@sankarmuniyappa,' '对于插入的文本,必须使用单引号。所以类似的东西 insert into orders_cancel_reasons_infos values (1,1,'Changed my mind',1), (2,2,'Quality not satisfactory',1)会起作用。您可以检查出更多的单,双引号。
dr0pdb

25

krokodilko的答案的简短版本:

insert into user_subservices(user_id, subservice_id) 
values(1, unnest(array[1, 2, 3]));

我认为这比已接受的答案更能表达意图。这是标准的SQL还是PostgreSQL特定的?
伯纳德

3
这两个答案都是特定于PostgreSQL的。接受的答案也许更容易翻译成其他数据库,例如Oracle : insert into user_subservices(user_id, subservice_id) select 1, column_value from table(sys.odcinumberlist(1,2,3))
yallie '17

谢谢,这在我看来比接受的答案更有意义,更易读。
霜冻的

1
一种将其与其他表中的信息一起使用的方式: insert into user_subservices(user_id, subservice_id) values(1, unnest(ARRAY(select id from subservices where name like '%test%')));
Efren

12

答案略有相关,因为每次尝试记住此解决方案时,我都会不断发现此问题。插入多行多列

insert into user_subservices (user_id, subservice_id)
select *
from unnest(array[1, 2], array[3, 4]);

3

更可靠的示例,用于需要为另一个表中的每一行向某个表中插入多行的情况:

INSERT INTO user_subservices (user_id, subservice_id)
SELECT users.id AS user_id, subservice_id
FROM users
CROSS JOIN unnest(ARRAY[1,2,3]) subservice_id;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.