首页 > 解决方案 > Postgres数组json最近日期

问题描述

我有一个这样的json数组:

[
  {
    "date": "26/11/2020 23:27",
    "note": "test1"
  },
  {
    "date": "22/11/2020 22:59",
    "note": "test2"
  },
  {
    "date": "18/11/2020 17:08",
    "note": "test3"
  }
]

我想采用具有最新数据的元素。

我获取第一个元素的旧查询是这样的:

(notes\:\:json->0)\:\:json->>'note' as note,
(notes\:\:json->0)\:\:json->>'date' as date_note

标签: jsonpostgresql

解决方案


分步演示:db<>fiddle

SELECT 
    elem.value ->> 'date' as thedate,
    elem.value ->> 'note' as note
FROM t,
    json_array_elements(data) elem                                  -- 1 
WHERE id = 4123
ORDER BY to_timestamp(elem ->> 'date', 'DD/MM/YYYY HH24:MI') DESC   -- 2
LIMIT 1                                                             -- 3
  1. 将所有数组元素提取到一行
  2. 从字段中读取日期时间字符串date,转换为时间戳,并使用它首先对具有最新时间戳的所有数组元素进行排序
  3. 只需返回第一个(= 最近的)数组元素。

推荐阅读