【问题标题】:Update jsonb column with value from row_to_json()使用 row_to_json() 中的值更新 jsonb 列
【发布时间】:2019-05-22 13:49:01
【问题描述】:

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

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 查询来执行此操作。

【问题讨论】:

    标签: sql json postgresql jsonb


    【解决方案1】:

    使用函数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)    
    

    【讨论】:

    • 抱歉没有具体说明,但如果我只想在 json_data 中包含一个特定的列,例如json_data 中的 col1 和 col2。我该怎么做?
    • 删除不需要的列,就像删除了 json_data 一样。
    • 你能举个例子吗?我不太确定(目前不在我的办公桌上)
    • 抱歉,这可以通过 col1、col2、col3 等有序属性来完成。我尝试了 to_jsonb 和 jsonb_build_object 但没有工作,例如它显示为 col2、col1、col3。我需要它与列的顺序相同
    • 我知道json是一个无序的值对集合但是可以修复吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2017-08-23
    • 1970-01-01
    相关资源
    最近更新 更多