sql - 在 JSONB 字段中循环 JSON 数组
问题描述
我想遍历列并获取相关对象的JSONB
某些值(price
、、discount_price
和)到我的过滤器。但我得到这个错误:currency
JSON
syntax error at or near "FOR"
parts
列的值为JSONB
:
[
{
"item_tags": ["black", "optional"],
"name": "Keyboard",
"price": 50,
"currency": "USD",
"discount_price": 40
},
{
"item_tags": ["white", "optional"],
"name": "Mouse",
"price": 40,
"currency": "USD",
"discount_price": 30
}
]
我的查询($1
是用户输入。可以是“可选”或“必需”):
SELECT
id,
title,
FOR element IN SELECT * FROM jsonb_array_elements(parts)
LOOP
CASE
WHEN element->'item_tags' @> $1
THEN SELECT element->>'discount_price' AS price, element->>'currency' AS currency
ELSE SELECT element->>'price' AS price, element->>'currency' AS currency
END
END LOOP
FROM items;
$1
如果等于“可选”,这是我想要得到的输出:
{
"id": 1,
"title": "example title",
"parts": [
{
"name": "Keyboard",
"discount_price": 40,
"currency": "USD"
},
{
"name": "Mouse",
"discount_price": 30,
"currency": "USD"
}
]
}
非常感谢任何帮助。我遵循官方文档,但它不适合初学者。我使用 PostgreSQL 13。
解决方案
您需要取消嵌套数组,过滤掉不需要的部分,删除不需要的键,然后将更改的部分聚合回 JSON 数组。
这可以使用标量子查询来完成:
select id, title,
(select jsonb_agg(x.part - 'item_tags')
from jsonb_array_elements(i.parts) as x(part)
where (x.part -> 'item_tags') ? 'optional')
from items i;
该表达式从 JSON 对象x.part - 'item_tags'
中删除键。运算符测试数组是否包含右侧的字符串item_tags
。然后将这些 JSON 值聚合回一个数组。?
item_tags
jsonb_agg()
'optional'
您可以在字符串的位置传递您的参数。
推荐阅读
- postgresql - 无法从表中选择变量(Postgresql)
- ruby-on-rails - 提交到数据库后将String转换为Hash
- react-scripts - 全局设置反应脚本
- r - 递归估计的收益波动率
- python-3.x - 我是编码新手,如果我的问题很愚蠢,请原谅我,但我可以知道如何找到每个学生的考试总分吗?
- list - 在初始化程序中只能访问静态成员,错误
- javascript - 具有同一类的多个实例的类构造函数依赖关系
- javascript - 更改网站中的 url 链接语言
- qemu - qemu 从 xml 到本机分配 PCI 设备
- docker - 带有 monorepos 的 Docker - 在子存储库之间共享文件