我有一个包含如下数据的表:
col1 col2 col3 col4 json_data
----------------------------------------------------
a b c d {"mock":"abc123"}
e f g h {"mock":"def456"}
json_data
列是一个 jsonb 类型的列,其中包含一些与我想使用 row_to_json()
函数更新的任何内容无关的 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)
关于sql - 使用 row_to_json() 中的值更新 jsonb 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56258399/