Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 在psql中更新json列_Postgresql_Postgresql 12 - Fatal编程技术网

Postgresql 在psql中更新json列

Postgresql 在psql中更新json列,postgresql,postgresql-12,Postgresql,Postgresql 12,我有一个包含json列的表。json值将如下所示: {'john':1,'alex':4,'harry':2} 如果我想为john添加1,我将如何执行此操作? 获取您的数据。如果它的类型为json,则将其转换为jsonb 请求元素的路径为text数组 获取原始值->运算符返回类型text,因此要执行整数操作,需要将其转换为类型int。然后添加1。此结果必须重新转换为类型jsonb。不幸的是,typeint不能直接转换为typejsonb,因此通过typetext 使用jsonb_set()更新

我有一个包含json列的表。json值将如下所示:

{'john':1,'alex':4,'harry':2}
如果我想为john添加1,我将如何执行此操作?

  • 获取您的数据。如果它的类型为
    json
    ,则将其转换为
    jsonb
  • 请求元素的路径为
    text
    数组
  • 获取原始值
    ->
    运算符返回类型
    text
    ,因此要执行
    整数
    操作,需要将其转换为类型
    int
    。然后添加
    1
    。此结果必须重新转换为类型
    jsonb
    。不幸的是,type
    int
    不能直接转换为type
    jsonb
    ,因此通过type
    text
  • 使用
    jsonb_set()
    更新(1)中指定的JSON对象
  • 如果您的列的类型是
    json
    而不是
    jsonb
    ,请将结果转换回类型
    json
  • 执行更新

  • 非常感谢。如果我有这样一个json对象:{'john':{'age':1},'alex':{'age':4},'harry':{'age':2},它是类似的。您只需修改指向对象的路径:
    jsonb_集(mydata::jsonb,{john},((mydata->'john')::int+1)::text::jsonb::json
    UPDATE mytable                                    -- 6
    SET mydata = jsonb_set(                           -- 4
        mydata::jsonb,                                -- 1
        '{john}',                                     -- 2
        ((mydata ->> 'john')::int + 1)::text::jsonb   -- 3
    )::json;                                          -- 5