【问题标题】:Postgres array json recent datePostgres数组json最近日期
【发布时间】:2020-12-07 15:00:56
【问题描述】:

我有一个这样的 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

【问题讨论】:

    标签: json postgresql


    【解决方案1】:

    step-by-step demo: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. 只返回第一个(= 最近的)数组元素。

    【讨论】:

    • 有什么办法可以改变这个查询吗?select (tb.notes::json->0)::json->>'note' as note, (tb.notes::json-> 0)::json->>'date' as date_note from table as tb where id = 4545
    • 我需要直接提取最近日期的数组
    • dbfiddle.uk/… 当然。只需添加 WHERE 子句来过滤 id 并从 value 中提取元素
    猜你喜欢
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多