更新JSON数组的某些元素的数组PostgreSQL中的9.4 [英] Update certain array elements of a json array in PostgreSQL 9.4

查看:832
本文介绍了更新JSON数组的某些元素的数组PostgreSQL中的9.4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的一个表;

CREATE TABLE test (
  id BIGSERIAL PRIMARY KEY,
  data JSONB
);

INSERT INTO test(data) VALUES('[1,2,"a",4,"8",6]'); -- id = 1
INSERT INTO test(data) VALUES('[1,2,"b",4,"7",6]'); -- id = 2

如何更新元素数据 - > 1 数据 - > 3 成别的东西没有 PL / *

推荐答案

您不能处理的选择元素的 JSON / jsonb 直接输入。功能对于仍处于的Postgres 9.4失踪(见@克雷格的评论)。你必须做3个步骤:

You cannot manipulate selected elements of a json / jsonb type directly. Functionality for that is still missing in Postgres 9.4 (see @Craig's comment). You have to do 3 steps:


  1. UNNEST /分解JSON值。

  2. 操纵选中的元素。

  3. 聚合/组合的价值又回来了。

要更换JSON数组的 3元数据 - > 3 )使用行中的ID = 1 与给定的(新)值('< NEW_VALUE> )的PG 9.4

To replace the 3rd element of the json array (data->3) in the row with id = 1 with a given (new) value ('<new_value>') in pg 9.4:

UPDATE test t
SET    data = t2.data
FROM  (
   SELECT id, array_to_json(
                 array_agg(CASE WHEN rn = 1 THEN '<new_value>' ELSE elem END))
              ) AS data
   FROM   test t2
        , json_array_elements_text(t2.data) WITH ORDINALITY x(elem, rn)         
   WHERE  id = 1
   GROUP  BY 1
   ) t2
WHERE  t.id = t2.id
AND    t.data <> t2.data; -- avoid empty updates

关于 json_array_elements_text()

  • How to turn json array into postgres array?

关于与序数

  • PostgreSQL unnest() with element number

这篇关于更新JSON数组的某些元素的数组PostgreSQL中的9.4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆