[英]Query complicated array in a JSONB in Postgres
我有一個JSONB字段值:
{
"status":200,
"response":{
"page":1,
"limit":10,
"total":4,
"orders":[
{
"id":40201
},
{
"id":40111
}
]
}
}
如何查詢id = 40201的訂單數組對象?
我正在嘗試使用response-> orders-> [id:40201]查詢所有行
如果您知道這是數組中的第一個對象(從零開始!):
SELECT
yourjson -> 'response' -> 'orders' -> 0
如果沒有,則必須使用jsonb_array_elements()
將數組擴展為每個元素一行,並過濾每一行:
SELECT
elems.value
FROM
yourtable,
jsonb_array_elements(yourjson -> 'response' -> 'orders') elems
WHERE
elems ->> 'id' = '40201'
我將為此使用一個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');
或者使用@>
contains運算符:
select *
from the_table
where exists (select *
from jsonb_array_elements(the_json_column -> 'response' -> 'orders') as x (o)
where x.o @> '{"id" : 40201}';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.