使用 row_to_json() 中的值更新 jsonb 列

Update jsonb column with value from row_to_json()

我有一个 table 包含如下数据:

col1       col2     col3     col4      json_data  
----------------------------------------------------
 a           b        c       d       {"mock":"abc123"}
 e           f        g       h       {"mock":"def456"}

json_data 是 jsonb 类型的列,其中包含一些 json 与我想使用 row_to_json() 函数更新的任何内容无关。结果应该是这样的

col1       col2     col3     col4      json_data  
----------------------------------------------------
 a           b        c       d       {"col1:"a", "col2:"b","col3:"c","col4:"d"}
 e           f        g       h       {"col1:"e", "col2:"f","col3:"g","col4:"h"}

将从 row_to_json 函数获取结果以更新每一行。我不确定如何使用 UPDATE 查询来执行此操作。

使用函数 to_jsonb()- 运算符从生成的 json 对象中删除列 json_data

create table my_table(col1 text, col2 text, col3 text, col4 text, json_data jsonb);
insert into my_table values
('a', 'b', 'c', 'd', '{"mock":"abc123"}'),
('e', 'f', 'g', 'h', '{"mock":"def456"}');

update my_table t
set json_data = to_jsonb(t)- 'json_data'
returning *;

 col1 | col2 | col3 | col4 |                      json_data                       
------+------+------+------+------------------------------------------------------
 a    | b    | c    | d    | {"col1": "a", "col2": "b", "col3": "c", "col4": "d"}
 e    | f    | g    | h    | {"col1": "e", "col2": "f", "col3": "g", "col4": "h"}
(2 rows)    

您可以删除不止一列,例如:

update my_table t
set json_data = to_jsonb(t)- 'json_data'- 'col3'- 'col4'
returning *;

 col1 | col2 | col3 | col4 |         json_data          
------+------+------+------+----------------------------
 a    | b    | c    | d    | {"col1": "a", "col2": "b"}
 e    | f    | g    | h    | {"col1": "e", "col2": "f"}
(2 rows)    

或者,您可以使用 jsonb_build_object() 而不是 to_jsonb()

update my_table t
set json_data = jsonb_build_object('col1', col1, 'col2', col2)
returning *;

 col1 | col2 | col3 | col4 |         json_data          
------+------+------+------+----------------------------
 a    | b    | c    | d    | {"col1": "a", "col2": "b"}
 e    | f    | g    | h    | {"col1": "e", "col2": "f"}
(2 rows)