Quantcast
Channel: How to do an update + join in PostgreSQL? - Stack Overflow
Viewing all articles
Browse latest Browse all 19

Answer by Ali for How to do an update + join in PostgreSQL?

$
0
0

The answer of Mark Byers is the optimal in this situation. Though in more complex situations you can take the select query that returns rowids and calculated values and attach it to the update query like this:

with t as (  -- Any generic query which returns rowid and corresponding calculated values  select t1.id as rowid, f(t2, t2) as calculatedvalue  from table1 as t1  join table2 as t2 on t2.referenceid = t1.id)update table1set value = t.calculatedvaluefrom twhere id = t.rowid

This approach lets you develop and test your select query and in two steps convert it to the update query.

So in your case the result query will be:

with t as (    select v.id as rowid, s.price_per_vehicle as calculatedvalue    from vehicles_vehicle v     join shipments_shipment s on v.shipment_id = s.id )update vehicles_vehicleset price = t.calculatedvaluefrom twhere id = t.rowid

Note that column aliases are mandatory otherwise PostgreSQL will complain about the ambiguity of the column names.


Viewing all articles
Browse latest Browse all 19

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>