我有一个JSONB字段值:
{
"status":200,
"response":{
"page":1,
"limit":10,
"total":4,
"orders":[
{
"id":40201
},
{
"id":40111
}
]
}
}
如何查询id = 40201的订单数组对象?
我正在尝试使用response-> orders-> [id:40201]
查询所有行答案 0 :(得分:1)
如果您知道这是数组中的第一个对象(从零开始!):
SELECT
yourjson -> 'response' -> 'orders' -> 0
如果没有,则必须使用jsonb_array_elements()
将数组扩展为每个元素一行,并过滤每一行:
SELECT
elems.value
FROM
yourtable,
jsonb_array_elements(yourjson -> 'response' -> 'orders') elems
WHERE
elems ->> 'id' = '40201'
答案 1 :(得分:1)
我将为此使用exists
查询:
select *
from the_table
where exists (select *
from jsonb_array_elements(the_json_column -> 'response' -> 'orders') as x (o)
where x.o ->> 'id' = 40201');
或者@>
包含运算符:
select *
from the_table
where exists (select *
from jsonb_array_elements(the_json_column -> 'response' -> 'orders') as x (o)
where x.o @> '{"id" : 40201}';