[英]checking json array with postgres
我在postgres中有一個遵循以下格式的JSONB數組。
{
"id" : 22323,
"details" : [
{
"status" : "stage1",
"timestamp" : "2017-09-89"
},
{
"status" : "stage2",
"timestamp" : "2017-09-89"
}
]
}
我需要在stage2中獲取時間戳,如何在postgresql中選擇特定狀態的時間戳?
如果“ details”的索引始終與“ status”:“ stageVALUE的索引相同,則可以使用-> element,但是如果不這樣,則需要使用json_array_elements遍歷array的元素,例如:
t=# with b as (with v as (select '{
"id" : 22323,
"details" : [
{
"status" : "stage1",
"timestamp" : "2017-09-89"
},
{
"status" : "stage2",
"timestamp" : "2017-09-89"
}
]
}'::json j)
select json_array_elements(j->'details') j from v)
select j->>'timestamp' from b where j->>'status' = 'stage2'
;
?column?
------------
2017-09-89
(1 row)
並且如果stage2始終是第二個數組元素,則便宜一些:
t=# with v as (select '{
"id" : 22323,
"details" : [
{
"status" : "stage1",
"timestamp" : "2017-09-89"
},
{
"status" : "stage2",
"timestamp" : "2017-09-89"
}
]
}'::json j)
select j->'details'->1->>'timestamp' from v;
?column?
------------
2017-09-89
(1 row)
我使用索引1 cos數組從0開始索引
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.