Sql Postgres根据其他查询的结果从设置值更新
我被一个Sql Postgres根据其他查询的结果从设置值更新,sql,postgresql,sql-update,Sql,Postgresql,Sql Update,我被一个更新所困扰。我的桌子原来是: Clients ------------------ ID Emails Notification_type Contracts ------------------ ID Client_id (FK) Contracts_document_types ------------------ Contract_id (FK) Document_type_id (FK) 我可以根据客户表通知。然后我不得不改变通知方式。我的数据库更改为: Contracts
更新所困扰
。我的桌子原来是:
Clients
------------------
ID
Emails
Notification_type
Contracts
------------------
ID
Client_id (FK)
Contracts_document_types
------------------
Contract_id (FK)
Document_type_id (FK)
我可以根据客户
表通知。然后我不得不改变通知方式。我的数据库更改为:
Contracts_document_types
------------------
Contract_id (FK)
Document_type_id (FK)
Notification_method_id (FK)
Notification_methods
------------------
ID
emails
notification_type
我能够基于客户端创建必要的通知\u方法
条目,但我没有找到在合同\u文档\u类型中关联的方法。通知\u方法\u id
。可以根据客户
表找到通知方法
,但要更新的表是合同(文档)类型
,我不知道如何更新
我的想法是:
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 ????????
可以从客户机
(信息所在地)访问合同\u文档类型
,但我无法将它们与正确的用户关联。我在updatefrom
语句中遗漏了迭代过程的一些重要内容
简历:1客户有许多合同\文档\类型,我有一个基于客户创建的通知\方法。我找不到一种方法将正确的通知方法放在每个客户(该客户的所有合同文档类型)上。我的猜测是,它应该是这样工作的:
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;
您只是忘了添加合同
表作为缺少的链接。有关的详细信息
使用
只是一种语法速记。如果电子邮件
和通知类型
可能模棱两可,请明确表示:
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;
相关的:
cd
也应该起作用()——除非您使用的是非常旧的Postgres版本。该功能是在Postgres 8.2中引入的。这只是一个语法快捷方式,在这里很方便,完全是可选的。