如何在 postgres 中的 jsonb 单元格内按 limit 1 执行排序?
How to perform order by limit 1 inside a jsonb cell in postgres?
我在 postgres
中有一个 table
CREATE TABLE my_table (
id serial primary key,
col_1 jsonb,
....
里面col_1
,我有这样的结构
[{"date": "2018-10-13", "val_1": 90.8, "val_2": 87.9},
{"date": "2018-10-03", "val_1": 90.2, "val_2": 83.2},
{"date": "2018-10-11", "val_1": 92.8, "val_2": 88.9},
...
]
现在我需要这样查询
SELECT "latest date from the jsonb" WHERE id = {some_id};
为了做到这一点,我应该能够 order/sort col_1
中的数组按日期降序排列(首先使用 to_date
函数转换日期字符串)然后获取该排序数组的第一个元素。我如何在 postgres 中执行此操作?
您应该使用函数 jsonb_array_elements():
取消嵌套 json 数组
select (jsonb_array_elements(col_1)->>'date')::date as date
from my_table
where id = 1
order by date desc
limit 1
date
------------
2018-10-13
(1 row)
我在 postgres
中有一个 tableCREATE TABLE my_table (
id serial primary key,
col_1 jsonb,
....
里面col_1
,我有这样的结构
[{"date": "2018-10-13", "val_1": 90.8, "val_2": 87.9},
{"date": "2018-10-03", "val_1": 90.2, "val_2": 83.2},
{"date": "2018-10-11", "val_1": 92.8, "val_2": 88.9},
...
]
现在我需要这样查询
SELECT "latest date from the jsonb" WHERE id = {some_id};
为了做到这一点,我应该能够 order/sort col_1
中的数组按日期降序排列(首先使用 to_date
函数转换日期字符串)然后获取该排序数组的第一个元素。我如何在 postgres 中执行此操作?
您应该使用函数 jsonb_array_elements():
select (jsonb_array_elements(col_1)->>'date')::date as date
from my_table
where id = 1
order by date desc
limit 1
date
------------
2018-10-13
(1 row)