Postgresql更新&内部加入

时间:2017-07-27 20:07:25

标签: postgresql

我正在尝试根据更新和内部联接查询从表:local.payments 更新表:local.import_payments 中的数据。我使用的查询:

Update local.import_payments
  Set local.import_payments.client_id = local.payments.payment_for_client__record_id,
local.import_payments.client_name = local.payments.payment_for_client__company_name,
local.import_payments.customer_id = local.payments.customer__record_id,
local.import_payments.customer_name = local.payment_from_customer,
local.import_payments.payment_id = local.payments.payment_id
From local.import_payments
Inner Join local.payments 
Where local.payments.copy_to_imported_payments = 'true'

local.import_payments中的client_id,client_name,customer_id,customer_name需要使用表local.payments中的值进行更新,具体取决于检查字段copy_to_imported_pa​​yments的条件。

执行查询时出现语法错误。我尝试了几件事,但他们没有用。任何人都可以查看查询并让我知道问题在哪里

2 个答案:

答案 0 :(得分:1)

请尝试以下

UPDATE local.import_payments 
Set local.import_payments.client_id = 
local.payments.payment_for_client__record_id,
local.import_payments.client_name = 
local.payments.payment_for_client__company_name,
local.import_payments.customer_id = local.payments.customer__record_id,
local.import_payments.customer_name = local.payment_from_customer,
local.import_payments.payment_id = local.payments.payment_id
FROM  local.payments as lpay
WHERE lpay.<<field>> = local.import_payments.<<field>>
AND local.payments.copy_to_imported_payments = 'true'

答案 1 :(得分:0)

您不应该为更新的列指定架构/表,只能为列名指定:

  

不要在目标列的规范中包含表的名称 - 例如,UPDATE table_name SET table_name.col = 1无效。

from the doc

除了自我加入的情况外,您不应该使用from子句中的更新表。

您可以使用&#34;列列表语法&#34;。

缩短查询时间
update local.import_payments as target
  set (
    client_id,
    client_name,
    customer_id,
    customer_name,
    payment_id) = (
    source.payment_for_client__record_id,
    source.payment_for_client__company_name,
    source.customer__record_id,
    source.payment_from_customer,
    source.payment_id)
from local.payments as source
where
  <join condition> and
  source.copy_to_imported_payments = 'true'