UPDATE statement with multiple joins in PostgreSQL

前端 未结 5 1849
说谎
说谎 2021-01-07 18:16

I\'m trying to update a table called incode_warrants and set the warn_docket_no to the viol_docket_no from the incode_violations

5条回答
  •  一个人的身影
    2021-01-07 18:59

    The same as valid UPDATE statement in Postgres:

    UPDATE incode_warrants iw
    SET    warn_docket_no = iv.viol_docket_no
    FROM   incode_warrantvs  iwvs
    JOIN   incode_violations iv ON iv.viol_citation_no = iwvs.warnv_citation_no
                               AND iv.viol_viol_no = iwvs.warnv_viol_no
    WHERE  iw.warn_rid = iwvs.warnv_rid;
    -- AND iw.warn_docket_no IS DISTINCT FROM iv.viol_docket_no -- see below
    

    You cannot just use a table alias in the FROM clause as target table in the UPDATE clause. The (one!) table to be updated comes right after UPDATE keyword (if we ignore a possible ONLY keyword in between). You can add an alias there if you want. That's the immediate cause of your error message, but there's more.

    The column to be updated is always from the one table to be updated and cannot be table-qualified.

    You don't need to repeat the target table in the FROM clause - except for special cases like this:

    • PostgreSQL: update with left outer self join ignored

    This optional addition can avoid pointless cost by suppressing updates that do not change anything:

    AND iw.warn_docket_no IS DISTINCT FROM iv.viol_docket_no
    

    See:

    • How do I (or can I) SELECT DISTINCT on multiple columns?

    More in the excellent manual on UPDATE.

提交回复
热议问题