postgresql 从postgres中的json结构查询数组中的最后一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25170775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Query last element in array from json structure in postgres
提问by Nano Documet
Let's say that we have the following
假设我们有以下内容
{ "items" :
[
{"id": 1},
{"id": 2},
{"id": 3}
]
}
How can I get the last element from the array in the given json structure? Getting the first one seems not that complicated
如何从给定的 json 结构中的数组中获取最后一个元素?获得第一个似乎没有那么复杂
SELECT t.column->'items'->0 AS elem
FROM tbl t
WHERE other_column = 20;
Thanks in advance!
提前致谢!
回答by ig0774
回答by Martin
In Postgres 9.5+ one can now use negative subscripts to achieve this.
在 Postgres 9.5+ 中,现在可以使用负下标来实现这一点。
For your case above, getting the last element could be achieved by:
对于上述情况,可以通过以下方式获取最后一个元素:
SELECT t.column->'items'->-1 AS elem
FROM tbl t
WHERE other_column = 20;