如何在postgres中更新JSONB数组

时间:2018-02-22 06:02:47

标签: sql arrays json postgresql

我有一个包含以下定义的表:

CREATE TABLE USER_CONFIGURATIONS (
  ID         BIGSERIAL PRIMARY KEY,
  DATA       JSONB
);

我有一个如下所示的数据字段:

[
    {
        "user_id": 1,       
        "user_name": "demo_user", 
        "is_manager": 1,        
        "options": [
            {
                "phone":{
                    "home":"XXXXXXX",
                    "work":"XXXXXXX"
                },
                "address":{
                    "home":"XXXXXXX",
                    "work":"XXXXXXX"
                }
            }
        ]
    },
    ...
]

的问题:

  • 如何更新" user_name" ?
  • 如何更新"选项 - >电话 - >家庭" ?

    UPDATE USER_CONFIGURATIONS SET DATA = jsonb_set(...)WHERE ... user_id = 1;

postgres 9.6版。 我尝试了jsonb_set()但没有尝试

1 个答案:

答案 0 :(得分:1)

input event

只需运行两次:

update USER_CONFIGURATIONS
set data =  
jsonb_set(
  jsonb_set(
    data,'{0,"user_name"}','"blah"'
  ), '{0,"options",0,"phone","home"}','999999'
)
where id =1
;