tim*_*dev 2 sql postgresql json sql-update jsonb
我在 Postgres(版本 10)中有一个表,其中包含一个可为空的 jsonb 列:
CREATE TABLE j_play (
id serial PRIMARY KEY,
created_ts TIMESTAMPTZ,
data JSONB
);
Run Code Online (Sandbox Code Playgroud)
可能最初插入的记录没有 json 数据,因此该列将为空。
| id | created_ts | data
| 1 | 2020-09-11 18:18:37.47755+00 | [null]
Run Code Online (Sandbox Code Playgroud)
我想更新此记录,以便如果 '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"}
Run Code Online (Sandbox Code Playgroud)
如果记录以一个空的 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
Run Code Online (Sandbox Code Playgroud)
但是当初始值为 NULL 时,我无法弄清楚如何做到这一点。我可能可以接受将列初始化为 {},但我想知道是否有一种优雅的方法可以将它从 NULL 更新。
我想更新此记录,以便如果 'null' 添加一个 json 对象,并且如果一个 json 对象已经存在,则对其进行修改。
使用coalesce():
update j_play set data = coalesce(data, '{}') || '{"a": "12345"}';
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
身份证 | created_ts | 数据
-: | :--------- | :---------------------------
1 | 空 | {“a”:“12345”,“b”:“54321”}