sql - 如何根据postgres中json数组中的键更新值?
问题描述
在一个表中有一个列 data(jsonb) 和这样的 json 数组
[
{"pid": "123", "percentage": "10"},
{"pid": "456", "percentage": "50"},
{"pid": "789", "percentage": "40"}
]
我想更新 pid 为 789 的百分比 30。我使用了这个查询但没有成功。
UPDATE table
SET data =
jsonb_set(data, '{pid}'::text[], data->'pid' || '{"percentage":"30"}'::jsonb)
WHERE (data->> 'pid') = '789' and id= '1'; [id is table's primary key]
解决方案
没有简单的方法可以做到这一点(除了将您的数据模型更改为正确规范化的模型)。您将不得不取消嵌套数组,并替换相关 PID 的百分比。然后将元素聚合回一个数组。
您也不能->>
在数组上使用,因为该运算符不适用于数组。
update the_table t
set data = (select jsonb_agg(case d.element ->> 'pid'
when '789' then d.element || '{"percentage": 30}'
else d.element
end)
from jsonb_array_elements(t.data) as d(element))
where id = 1
and data @> '[{"pid": "789"}]'
推荐阅读
- sql-server - SQL Server 2008 R2 : restrict server login from seeing all but 2 databases on server
- vue.js - 无法在 ag-grid Vue 中读取未定义的属性“setQuickFilter”
- linux-kernel - 在同一个等待队列上等待不同的条件还是为每个条件使用单独的等待队列?
- android - 构建包含依赖 AAR 的 Android 库 AAR
- java - 创建一个实现 View.OnClickListener 的动态 onClick()
- c# - 如何从 libtiff.net TIFFCP.exe 捕获 C# 中的所有异常
- outlook-api - Outlook 休息 api ErrorNonExistentMailbox
- git - git 服务器在哪里存储推送的文件以及在客户端克隆时从哪里获取?
- php - PHP日期,如何防止php日期自动转换为第二天?
- android - Android custom keyboard layouts switching