postgreSQL 如果不存在则添加带有值的新键,如果存在则编辑它

postgreSQL Adding New Key with value if it doesnt exist and edit it if it does

我正在尝试 运行 以下内容,但它不会更新具有 NULL 值的列或没有此键的列:

update A a set 
a.jsonbcolumn = ('{"key":' 1 '}')

我使用的是 postgres 9.6.3,jsonb_set 不适合我。有什么建议吗?

谢谢

jsonb_set() 是要走的路:

update a
  set jsonbcolumn = jsonb_set(jsonbcolumn, '{key}', '1');

如果它没有创建键,这可能是因为列值为 NULL 而不是空的 JSON。在那种情况下使用 coalesce():

update a
  set jsonbcolumn = jsonb_set(coalesce(jsonbcolumn,'{}'), '{key}', '1');

在线示例:https://rextester.com/MSU66547