如何在 PostgreSQL Update 语句中使用 From 子句

How to use From clause inside PostgreSQL Update statement

我正在将 SQL 存储过程转换为 PostgreSQL 存储函数。在 Update 内的这个存储函数中有 From 子句。

我想知道如何使用From inside Update?因为我收到错误 table name "account" specified more than once

CREATE OR REPLACE FUNCTION ETL_Insert_ModifyData( instID numeric)

  RETURNS void
  LANGUAGE 'sql'

AS $$ 

        --Account
        UPDATE account
        SET  namount = stg_account.namount, 
             slocation = stg_account.sLocation, 
             ndept_id = stg_account.ndept_id ,
             account.naccount_cpc_mapping_id = stg_account.naccount_cpc_mapping_id
        FROM account 
            INNER JOIN stg_account ON account.naccount_id = stg_account.naccount_id
            INNER JOIN department ON stg_account.ndept_id = department.ndept_id
            INNER JOIN accountcpcmapping ON stg_account.naccount_cpc_mapping_id = accountcpcmapping.naccount_cpc_mapping_id

        WHERE account.ninst_id = instID
            AND department.ninst_id = instID
            AND accountcpcmapping.ninst_id = instID

        --print 'Account completed '    

    $$

将带有 account table 和 stg_accountJOIN 条件移动到 WHERE 子句。此外,您无需在 SET 中引用 account

此外,更喜欢使用较短的别名(例如一个或两个字母)而不是使用完整的 table 名称。

UPDATE account
SET
    namount   = stg_account.namount,
    slocation = stg_account.sLocation,
    ndept_id  = stg_account.ndept_id ,
    naccount_cpc_mapping_id = stg_account.naccount_cpc_mapping_id
FROM stg_account
INNER JOIN department ON stg_account.ndept_id = department.ndept_id
INNER JOIN accountcpcmapping ON
    stg_account.naccount_cpc_mapping_id = accountcpcmapping.naccount_cpc_mapping_id
WHERE account.naccount_id   = stg_account.naccount_id
    AND account.ninst_id    = instID
    AND department.ninst_id = instID
    AND accountcpcmapping.ninst_id = instID