简体   繁体   中英

Update a table use result of another query in Postgres

I have a 2 table like this:

table1 : ( time, value, id ), table2 :( time, value, id, ... )

I need to update table1 with a result of a query on table2 based on id , for example the query can be:

SELECT * from table2 where value > 2

and this query returns more than hundreds of rows,

I need update table1 with these rows based on id ( set time=q.time, value=q.value where id=q.id ) is it possible with sql query?

I don't need UPSERT as I'm sure I have same id in both tables, just need update

Postgres supports a FROM clause for UPDATE :

update table1
   set time = q.time, 
       value = q.value
from table2 q
where table2.id = table1.id
  and table2.value > 2;
SELECT * 
into temp buffer     
from table2 
where value > 2;


insert into table1(list of columns to be updated)
select (list of columns to be selected)
from buffer;

NOTE___ --buffer is a temporary table that stores the output of the main query -- make sure both tables (table1 and table2) have the same columns and are arranged in the same order

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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