[英]Postgresql Update using Inner Join set
我有两个表,它们共享两个字段(myfield1,myfield2),并且两个表之一具有其他2个感兴趣的字段。
这是我要执行的操作:1.内部联接两个表2.使用另一个字段中的字段(字段或另一个字段)更新表2中的列(字段1),具体取决于字段是否为空。
下面的代码运行正常,但目标集字段(field1)并未进行任何更新。
Update Table2
Set field1 = (
CASE
WHEN os.afield is not null
THEN (os.afield)
Else os.anotherfield
End
)
from Table1 os
inner join Table2 fd
ON fd.myfield1= os.myfield1
AND fd.myfield2 = os.myfield2;
Update Table2 fd
Set fd.field1 =
(select CASE WHEN os.afield is not null THEN (os.afield) Else os.anotherfield End
from Table1 os
where fd.myfield1= os.myfield1
AND fd.myfield2 = os.myfield2);
这称为关联子查询,它针对Table2中的每一行执行。 但是您必须确保子查询返回单行或零行。
如果您只想更新表1中存在的那些行,那么此查询将更新表2中的所有行,您需要一个WHERE
Update Table2 fd
Set fd.field1 =
(select CASE WHEN os.afield is not null THEN (os.afield) Else os.anotherfield End
from Table1 os
where fd.myfield1= os.myfield1
AND fd.myfield2 = os.myfield2)
where exists (
select 1 from Table1 os
where fd.myfield1= os.myfield1
AND fd.myfield2 = os.myfield2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.