2014-10-28 90 views
0

我有两个表,他们共享两个字段(myfield1,myfield2)和两个表中的其中一个有两个其他感兴趣的领域。Postgresql更新使用内部联接集

这是我想做的事: 1.内加入表2中的两个表 2.更新一列(字段1)与任一领域(或更远anotherfield)从另一台视远处为空或不是。

下面的代码运行良好,但目标设置字段(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; 

回答

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

这就是所谓的这对表2中的每一行执行相关子查询。但是你必须确定子查询返回单行或零行。

此查询,如果您想更新只存在于表1行,你需要一个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); 
将更新表2中的所有行