[英]Postgres Nested JSONB Query
I have a JSONB column, data, in the orders table:我在订单表中有一个 JSONB 列数据:
# orders.data
{
discount_codes: [
{ code: 'foo' },
{ code: 'bar'}
]
}
# codes_array: ['foo', 'bar', 'baz']
I'm trying to select "orders where discount_codes contain a code in codes_array".我正在尝试 select“discount_codes 包含代码数组中的代码的订单”。 I could not figure out how to write this query exactly.我不知道如何准确地编写这个查询。 I read about the [*] operator but am unsure how to use it in this context.我阅读了有关 [*] 运算符的信息,但不确定如何在这种情况下使用它。
This only searches the first element of discount_codes:这仅搜索 discount_codes 的第一个元素:
SELECT *
FROM ORDERS
WHERE data->'discount_codes'->0->'code' ?| array['foo','bar','baz']
This only searches for 'foo'.这仅搜索“foo”。
SELECT *
FROM ORDERS
WHERE data @@ '$.discount_codes[*].code == "foo"'
I've been reading the docs https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-SQLJSON-PATH but I'm a bit lost.我一直在阅读文档https://www.postgresql.org/docs/12/functions-json.html#FUNCTIONS-SQLJSON-PATH但我有点迷路了。
You can extract all codes into an array, then apply the ?|
您可以将所有代码提取到一个数组中,然后应用?|
operator on that array:该数组上的运算符:
select *
from orders
where jsonb_path_query_array(data, '$.discount_codes[*].code') ?| array['foo','bar','baz']
The expression jsonb_path_query_array(data, '$.discount_codes[*].code')
returns ["foo", "bar"]
for your sample JSON表达式jsonb_path_query_array(data, '$.discount_codes[*].code')
为您的示例 JSON 返回["foo", "bar"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.