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

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

$
0
0

Let me explain a little more by my example.

Task: correct info, where abiturients (students about to leave secondary school) have submitted applications to university earlier, than they got school certificates (yes, they got certificates earlier, than they were issued (by certificate date specified). So, we will increase application submit date to fit certificate issue date.

Thus. next MySQL-like statement:

UPDATE applications aJOIN (    SELECT ap.id, ab.certificate_issued_at    FROM abiturients ab    JOIN applications ap     ON ab.id = ap.abiturient_id     WHERE ap.documents_taken_at::date < ab.certificate_issued_at) bON a.id = b.idSET a.documents_taken_at = b.certificate_issued_at;

Becomes PostgreSQL-like in such a way

UPDATE applications aSET documents_taken_at = b.certificate_issued_at         -- we can reference joined table hereFROM abiturients b                                       -- joined tableWHERE     a.abiturient_id = b.id AND                           -- JOIN ON clause    a.documents_taken_at::date < b.certificate_issued_at -- Subquery WHERE

As you can see, original subquery JOIN's ON clause have become one of WHERE conditions, which is conjucted by AND with others, which have been moved from subquery with no changes. And there is no more need to JOIN table with itself (as it was in subquery).


Viewing all articles
Browse latest Browse all 19

Trending Articles



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