简体   繁体   English

使用内部联接集的Postgresql更新

[英]Postgresql Update using Inner Join set

I have two tables that they share two fields (myfield1, myfield2) and one of the two tables has 2 other fields of interest. 我有两个表,它们共享两个字段(myfield1,myfield2),并且两个表之一具有其他2个感兴趣的字段。

Here is what I want to do: 1. Inner Join the two tables 2. Update a column (field1) in Table2 with either fields (afield or anotherfield) from the other table depending on afield is null or not. 这是我要执行的操作:1.内部联接两个表2.使用另一个字段中的字段(字段或另一个字段)更新表2中的列(字段1),具体取决于字段是否为空。

The code below runs fine but the targeted set field (field1) doesn't get updated with anything. 下面的代码运行正常,但目标集字段(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);

It's called a correlated subquery which is executed for each row in Table2. 这称为关联子查询,它针对Table2中的每一行执行。 But you must be sure that subquery returns single or zero rows. 但是您必须确保子查询返回单行或零行。

This query will update all rows in Table2 if you want to update only those rows which exist in Table1 you need a WHERE 如果您只想更新表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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM