我有一个表,其中有一列名为“数据”,类型为 JSONB。我正在尝试提出一个 SQL 语句来适应最近的模型更改。 (postgres 9.4)
旧模型中的“isIndiaGSTComposition”需要更改为新模型中的“auxiliaryProperties”数据结构(如下)。
{
"test":{
"isIndiaGSTComposition":true (boolean)
}
}
新模型:
{
"test":{
"AuxiliaryProperties":[
{
"id":"indiaGSTComposition",
"booleanValue":true
}
]
}
}
请注意,如果 isIndiaGSTComposition 为 null,则它应该为 auxiliaryProperties : null。但如果它有 true 或 false,则需要采用上述数据结构格式(如上面的“新模型”示例)。
感谢任何帮助。提前致谢!
最佳答案
你可以编写转换函数并使用
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()
用 “id”
和 “booleanValue”
填充 “AuxiliaryProperties”
。
然后再次使用 jsonb_insert()
以 "AuxiliaryProperties"
键插入新的子对象,并使用 #-
运算符删除旧的子对象。
关于json - Postgresql - 更新 JSONB 列类型的 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47395492/