简体   繁体   English

使用 Postgres,如果为 NULL,我如何使用 UPDATE 插入新的 jsonb 值,或者如果值已经存在则修改 json?

[英]With Postgres, how can I use UPDATE to insert a new jsonb value if NULL, or amend the json if a value already exists?

I have a table in Postgres (version 10) that contains a nullable jsonb column:我在 Postgres(版本 10)中有一个表,其中包含一个可为空的 jsonb 列:

CREATE TABLE j_play (
id                  serial PRIMARY KEY,
created_ts          TIMESTAMPTZ,
data                JSONB
); 

It is possible that records may initially be inserted with no json data, and so the column will be null.可能最初插入的记录没有 json 数据,因此该列将为空。

| id | created_ts                   | data
| 1  | 2020-09-11 18:18:37.47755+00 | [null]

I want to update this record so that if 'null' a json object is added, and if a json object already exists then it is amended.我想更新此记录,以便如果 'null' 添加一个 json 对象,并且如果一个 json 对象已经存在,则对其进行修改。

UPDATE j_play SET data = '{"a": "12345"}'
| id | created_ts                   | data
| 1  | 2020-09-11 18:18:37.47755+00 | {"a": "12345"}

UPDATE j_play SET data = '{"b": "54321"}'   -- This is obviously bogus but the intention is to amend existing json
| id | created_ts                   | data
| 1  | 2020-09-11 18:18:37.47755+00 | {"a": "12345", "b": "54321"}

If the record starts with an empty json document then I can use jsonb_set:如果记录以一个空的 json 文档开头,那么我可以使用 jsonb_set:

| id | created_ts                   | data
| 1  | 2020-09-11 18:18:37.47755+00 | {}
UPDATE j_play SET data = jsonb_set(rec_data, '{a}', '"12345"', TRUE) WHERE id = 1

But I can't work out how to do this when the initial value is NULL.但是当初始值为 NULL 时,我无法弄清楚如何执行此操作。 I can probably live with initialising the column to {} but I wondered if there was an elegant way to update it from NULL.我可能可以接受将列初始化为 {},但我想知道是否有一种优雅的方法可以将它从 NULL 更新。

I want to update this record so that if 'null' a json object is added, and if a json object already exists then it is amended.我想更新此记录,以便如果 'null' 添加一个 json 对象,并且如果一个 json 对象已经存在,则对其进行修改。

Use coalesce() :使用coalesce()

update j_play set data = coalesce(data, '{}') || '{"a": "12345"}';

Demo on DB Fiddle : DB Fiddle 上的演示

insert into j_play (data) values(null);

update j_play set data = coalesce(data, '{}') || '{"a": "12345"}';
update j_play set data = coalesce(data, '{}') || '{"b": "54321"}';

select * from j_play;
id | created_ts | data                        
-: | :--------- | :---------------------------
 1 | null       | {"a": "12345", "b": "54321"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM