如何避免 `select sum() into` 在 PostgreSQL 中将目标变量设置为空

How to avoid a `select sum() into` set target variables to null in PostgreSQL

这个 select sum() 是触发器功能的一部分,它正在正确启动,

-- loop over all order lines without grouping
select
  sum(tp.pack_volume),
  sum(tp.pack_mass),
  sum(tl.qty_ordered),
  sum(tl.qty_fulfilled)
into
  new.pack_expected_volume,
  new.pack_expected_mass,
  new.qty_ordered,
  new.qty_fulfilled
from 
  order_lines tl
join 
  product tp on tl.product_id = tp.id
where
  tl.order_id = new.id;

-- avoid nulls if no rows in of_order_lines
new.pack_expected_volume = coalesce (new.pack_expected_volume, 0);
new.pack_expected_mass = coalesce (new.pack_expected_mass, 0);
new.qty_ordered = coalesce (new.qty_ordered, 0);
new.qty_fulfilled = coalesce (new.qty_fulfilled, 0);

但是,我不得不添加那些可怕的 coalesce 行来检查 none 的聚合结果是否为空。当 table order_lines.

中没有行时,这肯定会发生

有人知道更 elegant/clean 的方法吗,无需在 select 之后重新检查空值?

只需在 SELECT 列表中执行此操作:

select
  coalesce(sum(tp.pack_volume),0),
  coalesce(sum(tp.pack_mass),0),
  coalesce(sum(tl.qty_ordered),0),
  coalesce(sum(tl.qty_fulfilled),0)
into
  new.pack_expected_volume,
  new.pack_expected_mass,
  new.qty_ordered,
  new.qty_fulfilled
from 
  order_lines tl
...