PostgreSQL SELECT 基于 JSON 对象中的值

PostgreSQL SELECT based on value in JSON object

我想查询 table、orders 和 select 基于列中 json 对象中的值的所有行,updates.

我想 select 上次关闭后 5 天内的所有行。

这是一个 PostgreSQL 12 数据库。

[
  {
    "time": {
      "__type": "Date",
      "iso": "2021-09-16T09:31:57.976Z"
    },
    "userId": "xKn5A1GuLV",
    "to": "created",
    "role": "admin"
  },
  {
    "time": {
      "__type": "Date",
      "iso": "2021-09-16T09:31:57.976Z"
    },
    "userId": "xKn5A1GuLV",
    "to": "opened",
    "role": "admin",
    "from": "created"
  },
  {
    "time": {
      "__type": "Date",
      "iso": "2021-10-12T12:10:44.688Z"
    },
    "userId": "Hd37AyKJsN",
    "to": "closed",
    "role": "admin",
    "from": "opened"
  },
  {
    "time": {
      "__type": "Date",
      "iso": "2021-10-12T12:10:54.224Z"
    },
    "userId": "Hd37AyKJsN",
    "to": "opened",
    "role": "admin",
    "from": "closed"
  },
  {
    "time": {
      "__type": "Date",
      "iso": "2021-10-12T12:40:58.476Z"
    },
    "userId": "Hd37AyKJsN",
    "to": "closed",
    "role": "admin",
    "from": "opened"
  }
]

如果您在 updates 列中有对象,例如:

{
    "time": {
      "__type": "Date",
      "iso": "2021-10-12T12:10:54.224Z"
    },
    "userId": "Hd37AyKJsN",
    "to": "opened",
    "role": "admin",
    "from": "closed"
}

然后查询将类似于:

select * from orders where (updates #>> 'time,iso')::timestamp Between NOW() - INTERVAL '5 day' AND NOW();

如果您在 updates 列中有数组,例如:

[{
    "time": {
      "__type": "Date",
      "iso": "2021-10-12T12:10:54.224Z"
    },
    "userId": "Hd37AyKJsN",
    "to": "opened",
    "role": "admin",
    "from": "closed"
}]

然后查询将类似于:

select * from orders where (updates #>> '0,time,iso')::timestamp Between NOW() - INTERVAL '5 day' AND NOW();