Postgresql - 用于更新JSONB列类型的SQL

问题描述 投票:1回答:1

我有一个表,其中有一个名为“data”的列,类型为JSONB。我试图提出一个SQL语句来适应最近的模型更改。 (postgres 9.4)

旧模型中的“isIndiaGSTComposition”需要在新模型中作为“auxiliaryProperties”数据结构(下面)进行更改。

 {  
   "test":{  
      "isIndiaGSTComposition":true        (boolean)
   }
}

新模式 :

{  
   "test":{  
      "AuxiliaryProperties":[
                   {
                    "id":"indiaGSTComposition",
                    "booleanValue":true
                    }
                  ]        
   }
}

请注意,如果isIndiaGSTComposition为null,则它应为auxiliaryProperties:null。但如果它有真或假,则需要采用上述数据结构格式(如上面的“新模型”示例)。

任何帮助表示赞赏。提前致谢 !

json postgresql postgresql-9.4 jsonb
1个回答
0
投票

你可以编写转换函数和使用

UPDATE table
SET field = conv_func(field);

所有JSON操作都是here(选择你的PostgreSQL版本)。

使用json->'test'运算符获取'test'的子对象:

{  
      "isIndiaGSTComposition":true        (boolean)
}

如果您有多个字段,则可以使用它们进行迭代

FOR _rec IN
SELECT t."key", t."value"
FROM jsonb_each(subobject) t
LOOP
...
END LOOP;

为新的"AuxiliaryProperties"子对象声明新的JSONB变量并使用'{}'::jsonb初始化它

使用jsonb_insert()"AuxiliaryProperties""id"填充"booleanValue"

然后再次使用jsonb_insert()插入带有密钥"AuxiliaryProperties"的新子对象,并使用#-运算符删除旧的子对象。

© www.soinside.com 2019 - 2024. All rights reserved.