使用另一个表的聚合有效地更新表

时间:2014-03-11 16:56:06

标签: sql postgresql

我正在使用

UPDATE main 
SET val = (
    SELECT SUM(..) 
    FROM other 
    WHERE main.id=other.main_id 
    GROUP BY main_id
)

然而,其他具有可选参与,因此当它运行时,如果在另一个表中找不到val,则更新似乎为null。相反,它应该只更新子查询中存在的id的val。

我该如何解决这个问题?

编辑: 我设法通过添加

来修复它
WHERE IN SELECT main_id FROM other 

2 个答案:

答案 0 :(得分:2)

update main 
set val = coalesce(
    select sum(..) 
    from other 
    where main.id=other.main_id 
    group by main_id
), val)

如果子查询返回null,则会将val设置为val

或更好

update main 
set val = s.val_sum
from (
    select sum(..) as val_sum, main_id 
    from other 
    group by main_id
) s
where s.main_id = main.id

答案 1 :(得分:0)

UPDATE main SET val = 
   (SELECT count(*) FROM other WHERE main.id=other.main_id)
WHERE exists (select 1 from other where main.id=other.main_id)