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

时间:2019-05-22 13:49:02

标签: sql json postgresql jsonb

我有一个表,其中包含如下数据:

WSS4JInInterceptor

col1 col2 col3 col4 json_data ---------------------------------------------------- a b c d {"mock":"abc123"} e f g h {"mock":"def456"} 是jsonb类型的列,其中包含一些与我想使用json_data函数进行更新的内容无关的json。结果应该是这样的

row_to_json()

它将从row_to_json函数获取结果以更新每一行。我不确定如何使用UPDATE查询来做到这一点。

1 个答案:

答案 0 :(得分:2)

使用函数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)    
相关问题