以下是在 Postgres 9.4.4 中以 json
数据类型存储的数据示例:
[
1479772800000,
70.12
],
[
1479859200000,
70.83
],
[
1480032000000,
71.23
]
如何选择此数组的最后一个元素:[1480032000000,71.23]
\d stocks
Table "public.stocks"
Column | Type | Modifiers
------------------+----------------------+-----------------------------------------------------
id | integer | not null default nextval('stocks_id_seq'::regclass)
ticker | character varying(6) |
price_history | json |
Indexes:
"stocks_pkey" PRIMARY KEY, btree (id)
"ix_stocks_ticker" UNIQUE, btree (ticker)
最佳答案
您可以通过以下方式获取 Postgres JSON 数组的最后一个元素(已知在 Postgres 9.5+ 中有效):
select '...'::json->-1;
这使用 ->
运算符。负整数从末尾开始计数。
例如:
select '[[1479772800000, 70.12], [1479859200000, 70.83], [1480032000000, 71.23]]'::json->-1;
关于arrays - 在 JSON 列类型中查找数组的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40825114/