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

标签 sql json postgresql jsonb

我有一个包含如下数据的表:

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/

相关文章:

php - 我如何使用一个表项中的 id 连接另一个表项

python - 只打开和读取最新的 json 文件一次

java - 将InputStream解析为Json对象并获取值

sql - Postgres : Find "from this table" foreign keys (Faster alternative)

sql - 如何在字符串中动态确定的位置选择动态数量的子字符串?

node.js - sequelize-auto TypeError : connection. query(...).on 不是函数

sql - 从 SQL 中划分结果时出错

php - 计算每列的值

sql - 使用 LIKE 获取仅包含特定字符的记录

java - 如何将 LinkedHashSet 集合添加到 JsonObjectBuilder 对象?