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

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

$
0
0

To add something quite important to all the great answers above, when you want to update a join-table, you may have 2 problems:

  • you cannot use the table you want to update to JOIN another one
  • Postgres wants a ON clause after the JOIN so you cannot only use where clauses.

This means that basically, the following queries are not valid:

UPDATE join_a_bSET count = 10FROM aJOIN b on b.id = join_a_b.b_id -- Not valid since join_a_b is used hereWHERE a.id = join_a_b.a_idAND a.name = 'A'AND b.name = 'B'
UPDATE join_a_bSET count = 10FROM aJOIN b -- Not valid since there is no ON clauseWHERE a.id = join_a_b.a_id AND b.id = join_a_b.b_ida.name = 'A'AND b.name = 'B'

Instead, you must use all the tables in the FROM clause like this:

UPDATE join_a_bSET count = 10FROM a, bWHERE a.id = join_a_b.a_id AND b.id = join_a_b.b_id AND a.name = 'A'AND b.name = 'B'

It might be straightforward for some but I got stuck on this problem wondering what's going on so hopefully, it will help others.


Viewing all articles
Browse latest Browse all 19

Trending Articles



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