如何解决如何避免`select suminto`在PostgreSQL中将目标变量设置为null
此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
行以检查所有汇总结果都不为空。当表order_lines
中没有行时,肯定会发生这种情况。
有人知道一种更优雅/干净的方法,而无需在select
之后重新检查null吗?
解决方法
只需在SELECT列表中这样做:
select
coalesce(sum(tp.pack_volume),0),coalesce(sum(tp.pack_mass),coalesce(sum(tl.qty_ordered),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
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。