Postgres UPDATE FROM set value 根据其他查询的结果

Postgres UPDATE FROM set value according to result of other query

我受困于 UPDATE。我的 table 最初是:

Clients
------------------
ID
Emails
Notification_type

Contracts
------------------
ID
Client_id (FK)

Contracts_document_types
------------------
Contract_id (FK)
Document_type_id (FK)

我可以根据 Clients table 通知。然后我不得不更改通知方法。我的数据库更改为:

Contracts_document_types
------------------
Contract_id (FK)
Document_type_id (FK)
Notification_method_id (FK)

Notification_methods
------------------
ID
emails
notification_type

我能够根据客户创建必要的 notification_methods 条目,但我没有找到在 contracts_document_types.notification_method_id 中关联的方法。可以根据clientstable找到notification_method,但是要更新的table是contracts_document_types,我不知道怎么办。

我的想法是这样的:

update contracts_document_types
set notification_method_id = query.nm_id
from ( select NM.id as nm_id from notification_methods NM
       inner join clients C on C.emails = NM.emails 
             and C.notification_type = NM.notification_type    
) as query
where ????????

可以从 clients(信息所在的位置)到达 contracts_document_types,但我无法将它们与正确的用户相关联。我在 UPDATE FROM 语句中遗漏了一些关于迭代过程的重要信息。

简历:1个客户有很多contracts_document_types,我有一个notification_method是根据客户创建的。我找不到在每个客户端上放置正确 notification_method 的方法(来自该客户端的所有 contracts_document_types)。

我有根据的猜测,它应该是这样工作的:

UPDATE contracts_document_types cd
SET    notification_method_id = q.nm_id
FROM  (
   SELECT co.id AS co_id, nm.id AS nm_id
   FROM   contracts co
   JOIN   clients   cl ON cl.id = co.client_id
   JOIN   notification_methods nm USING (emails, notification_type)
   ) q
WHERE  cd.contract_id = q.co_id;

您只是忘记添加 contracts table 作为缺失 link。 UPDATE in the manual.

的详细信息

USING 只是一个语法 shorthand。如果 emailsnotification_type 可能是模棱两可的,请像您一样明确:

JOIN   notification_methods nm ON nm.emails = cl.emails
                              AND nm.notification_type = cl.notification_type

更简单,您甚至不需要子查询:

UPDATE contracts_document_types cd
SET    notification_method_id = nm.id
FROM   contracts co
JOIN   clients   cl ON cl.id = co.client_id
JOIN   notification_methods nm USING (emails, notification_type)
WHERE  cd.contract_id = co.id;

相关:

  • UPDATE from result of SELECT
  • Update a column of a table with a column of another table in PostgreSQL