A
A
Artem2018-03-13 15:23:07
PostgreSQL
Artem, 2018-03-13 15:23:07

Double join in update query?

Hello. There are two tables - note, contractor.
The note table contains two keys to the contractor table (fk_contractor_from, fk_contractor_to);
You need to make an update note according to the conditions from the contractor.
How to be?

UPDATE 
    delivery_note 
SET 
    fk_contractor_from = fk_contractor_to,
    fk_contractor_to = fk_contractor_from 
WHERE 
    fk_contractor_from IN(
        SELECT DISTINCT id_contractor FROM contractor WHERE "type" = 'WH'
    )
    AND
    fk_contractor_to IN (
        SELECT DISTINCT id_contractor FROM contractor WHERE "type" = 'DC'
    )

You need to get away from nested queries, something like this, only working:
UPDATE 
    delivery_note as dn
SET 
    dn.fk_contractor_from = dn.fk_contractor_to,
    dn.fk_contractor_to = dn.fk_contractor_from
JOIN contractor as c_from ON dn.fk_contractor_from = c_from.id_contractor
JOIN contractor as c_to ON dn.fk_contractor_to = c_to.id_contractor
WHERE
    c_from.type = 'WH'
    AND
    c_to.type = 'DC'

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Artem, 2018-03-14
@proudmore

UPDATE 
    delivery_note as dn
SET 
    fk_contractor_from = fk_contractor_to,
    fk_contractor_to = fk_contractor_from
FROM contractor c_from, contractor c_to
WHERE
    (c_from.type = 'WH' AND dn.fk_contractor_from = c_from.id_contractor)
    AND
    (c_to.type = 'DC' AND dn.fk_contractor_to = c_to.id_contractor)

M
Maxim Fedorov, 2018-03-13
@Maksclub

Found this example:

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

D
d-stream, 2018-03-13
@d-stream

In my opinion, in pg, as in ms, the update syntax with joins looks like this:
update tablex
set ....
from tablex
join ..
join ..
where ..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question