简体   繁体   中英

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.

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.

The code below runs fine but the targeted set field (field1) doesn't get updated with anything.

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. 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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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