Postgres "UPDATE FROM VALUES"具有不同数量的可为空列?



values()要求每行具有相同数量的列。有时,我想为不同的行更新不同的列。如果列不能为null,我可以做如下操作:

update test set
foo = coalesce(t.foo, foo),
bar = coalesce(t.bar, bar)
from (values
(1, 'foo val', null),
(2, null, 'bar val')  
) as t(id, foo, bar) 
where t.id = test.id;

但是,如果列是可以为null的,那么这将不起作用。有没有一种方法可以使这种方法适用于可为null的列?

您可以选择一些对类型有效的特殊值,但永远不会在表中实际使用。那么该值可以表示";保持旧价值";。如果没有,那么您可能需要更多的列。

update test set
foo = case when not set_foo_null then coalesce(t.foo, test.foo) end,
bar = case when not set_bar_null then coalesce(t.bar, test.bar) end
from (values
(1, 'foo val', null, false, true),
(2, null, 'bar val', false, false)  
) as t(id, foo, bar, set_foo_null, set_bar_null) 
where t.id = test.id;

当然,还有很多其他的方法可以表述,也许更好的方法是将bool命名为"bool";keep_old_foo"则foo = case when keep_old_foo then test.foo else t.foo end

最新更新