Come inserire valori in una tabella da una query di selezione in PostgreSQL?

Ho una tabella items (item_id serial, name varchar(10), item_group int) e una tabella items_ver (id serial, item_id int, name varchar(10), item_group int).

Ora voglio inserire una riga in items_ver da items. Esiste una sintassi SQL breve per farlo?

Ho provato con:

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

ma ottengo un errore di sintassi:

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

Ora ho provato:

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

Ha funzionato meglio ma ho un errore:

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; 

Ciò può essere dovuto al fatto che le colonne sono definite in un ordine diverso nelle tabelle. Lordine delle colonne è importante? Speravo che PostgreSQL corrispondesse ai nomi delle colonne.

Risposta

Lordine delle colonne è importante, quindi se (e solo se) lordine delle colonne match puoi ad esempio:

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

Oppure, se non corrispondono, potresti ad esempio:

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

ma fare affidamento sullordine delle colonne è un bug in attesa di verificarsi (può cambiare, così come il numero di colonne) – rende anche il tuo SQL più difficile da leggere

Non cè niente di buono scorciatoia “- dovresti elencare esplicitamente le colonne sia per la tabella in cui stai inserendo che per la query che stai utilizzando per i dati di origine, ad esempio:

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

dbfiddle qui

Risposta

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

Per la stessa tabella

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

Risposta

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; 

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *