我正在使用
UPDATE main
SET val = (
SELECT SUM(..)
FROM other
WHERE main.id=other.main_id
GROUP BY main_id
)
但是 other 有可选的参与,所以当它运行时,如果在 other 表中找不到它,update 似乎会使 val 无效。相反,它应该只更新子查询中存在的 id 的 val。
我该如何解决这个问题?
编辑: 我设法通过添加来修复它
WHERE IN SELECT main_id FROM other
最佳答案
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
关于sql - 有效地使用另一个表的聚合更新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22331421/