如何在PostgreSQL中的选择查询中将值插入表中?


198

我有一张桌子items (item_id serial, name varchar(10), item_group int)和一张桌子items_ver (id serial, item_id int, name varchar(10), item_group int)

现在我想插入行items_veritems。有没有简短的SQL语法可以做到这一点?

我尝试过:

INSERT INTO items_ver VALUES (SELECT * FROM items WHERE item_id = 2);

但我收到语法错误:

ERROR:  syntax error at or near "select"
LINE 1: INSERT INTO items_ver VALUES (SELECT * FROM items WHERE item...

我现在尝试:

INSERT INTO items_ver SELECT * FROM items WHERE item_id = 2;

它工作得更好,但出现错误:

ERROR:  column "item_group" is of type integer but expression is of type 
character varying
LINE 1: INSERT INTO items_ver SELECT * FROM items WHERE item_id = 2;

这可能是因为在表中以不同顺序定义了列。列顺序重要吗?我希望PostgreSQL与列名匹配。

Answers:


288

列顺序确实很重要,因此例如(且仅当)列顺序匹配时,您才能:

insert into items_ver
select * from items where item_id=2;

或者,如果它们不匹配,您可以例如:

insert into items_ver(item_id, item_group, name)
select * from items where item_id=2;

但是依靠列顺序是一个等待发生的错误(它可以更改,列数也可以更改)-这也使您的SQL难以阅读

没有好的“捷径”-您应该为要插入的表和用于源数据的查询显式列出列,例如:

insert into items_ver (item_id, name, item_group)
select item_id, name, item_group from items where item_id=2;

dbfiddle 在这里


5
INSERT INTO test_import_two (name, name1, name2) 
(SELECT name, name1, name2 FROM test_import_one WHERE id = 2)

对于同一张桌子

INSERT INTO test_import_three (id1, name1, name2) 
(SELECT 216 ,name1, name2 FROM test_import_three WHERE id = 4)

-1
INSERT INTO gate_pass(
     site_id, gate_pass_element, sequence_no, createdby, createddate, lastmodifiedby, lastmodifieddate)
SELECT 1,   gatepasselement, 3, 1,now(),1,now()  
FROM unnest(string_to_array('Bhushan,Amol,pallavi', E',')) as gatepasselement;
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.