如何在具有空值的列上使用`jsonb_set`

iff*_*ffi 8 postgresql json jsonb postgresql-9.6

我正在使用Postgres 9.6,我有一个JSONB列,其中有些行有NULL值,有些行有dict值,如{"notify": false}.

我想用更多的字典键/值对更新列值.

UPDATE accounts SET notifications =  jsonb_set(notifications, '{"alerts"}', 'false');
Run Code Online (Sandbox Code Playgroud)

适用于我已经拥有类似值的情况{"notify": false}.最终结果如预期的那样{"alerts": false, "notifications": false}.

但是我试图更新我们的价值NULL,数据库中没有任何更新.

你能告诉我如何更新这些NULL值,所以它们的最终结果将是像这样的值{"notify": false}.最终结果如预期的那样{"alerts": false}

kli*_*lin 14

用途coalesce():

UPDATE accounts 
SET notifications =  jsonb_set(coalesce(notifications, '{}'), '{"alerts"}', 'false')
Run Code Online (Sandbox Code Playgroud)

甚至更简单:

UPDATE accounts 
SET notifications =  coalesce(notifications, '{}') || '{"alerts": false}'
Run Code Online (Sandbox Code Playgroud)