我在postgres中有一个JSONB数组,格式如下。
{
"id" : 22323,
"details" : [
{
"status" : "stage1",
"timestamp" : "2017-09-89"
},
{
"status" : "stage2",
"timestamp" : "2017-09-89"
}
]
}
我需要在stage2获取时间戳,如何在postgresql中选择特定状态的时间戳?
答案 0 :(得分:1)
如果索引"详细信息"总是与" status":" stageVALUE相同,你可以使用 - >元素,但如果没有 - 你需要用json_array_elements迭代数组元素,如下所示:
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
索引