[英]Select data from a nested jsonb array in Postgres
I want to select the last value from an array nested like this:我想 select 嵌套这样的数组中的最后一个值:
{ tier: [
{ tier: [] },
{ tier: [] },
{ tier: [
{ tier: 1},
{ tier: 2},
{ tier: 3}, // < this item
]
},
]
}
I've tried to use something like this from other examples, but the syntax is eluding me.我尝试在其他示例中使用类似的内容,但语法让我难以理解。 I either get a 'column does not exist' or 'cannot extract elements from object'
我要么得到“列不存在”或“无法从对象中提取元素”
SELECT *,
t0->tier->(jsonb_array_length(t0->tier) - 1) t1,
t1->tier->(jsonb_array_length(t1->tier) - 1) t2,
t2->tier->(jsonb_array_length(t2->tier) - 1) t3,
FROM data t0
You can reference it by negative index:您可以通过负索引引用它:
SELECT t -> 'tier' -> -1 -> 'tier' -> -1
FROM data;
The -1 here references the last item of the array, which means you don't need to calculate how many elements there are.这里的 -1 引用了数组的最后一项,这意味着你不需要计算有多少元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.