postgresql - Postgres jsonb 嵌套数组追加
问题描述
我有一个带有jsonb
列的简单表
CREATE TABLE things (
id SERIAL PRIMARY KEY,
data jsonb
);
数据如下:
{
"id": 1,
"title": "thing",
"things": [
{
"title": "thing 1",
"moreThings": [
{ "title": "more thing 1" }
]
}
]
}
那么我如何附加到一个深度嵌套的数组中moreThings
呢?
对于单级嵌套数组,我可以这样做并且它有效:
UPDATE posts SET data = jsonb_set(data, '{things}', data->'things' || '{ "text": "thing" }', true);
但同样不适用于深度嵌套的数组:
UPDATE posts SET data = jsonb_set(data, '{things}', data->'things'->'moreThings' || '{ "text": "thing" }', true)
我怎样才能追加到moreThings
?
解决方案
它工作得很好:
UPDATE things
SET data =
jsonb_set(data,
'{things,0,moreThings}',
data->'things'->0->'moreThings' || '{ "text": "thing" }',
TRUE
)
WHERE id = 1;
如果你有一个只包含一个主键和一个jsonb
属性的表,并且你经常想jsonb
在数据库中操作它,那么你肯定做错了。如果您对数据进行更多规范化,您的生活将会轻松得多。
推荐阅读
- apache-kafka-streams - 在将 Ktable 实体化为 Topic 之前将其转换为 Streaming 有什么好处?
- docker - 启动 wolkenkit 失败
- sql - 来自 SQL 查询的 Spark 数据框
- javascript - 如果用户已登录,则更改路由名称和组件
- css - 围绕 SVG 的框的纵横比错误
- python - 是否有任何 Python 选项可用于 3D 线性分段/分段回归
- python - 计算矩阵中两行的所有组合的点积
- powershell - 使用 Powershell 如何从 Exchange 移动设备检索“策略应用程序状态”?
- jquery - 使用子行动态构建 HTML 表
- git - 具有永久本地更改的 git pull 的首选策略