Postgresql:使用jsonb字段查询时间范围

Postgresql: Query Between time range using jsonb field

我有一个包含两个字段的 table:

id(serial), data(jsonb)

在数据中,我有一个日期时间字段存储为 UNIX 时间戳的记录:

{"Device":132,"Datetime": 1434166552,...}

我正在尝试在范围之间查询:

SELECT *
FROM trips
WHERE data->>'Datetime' BETWEEN
    EXTRACT(EPOCH FROM date '2014-04-01') AND
    EXTRACT(EPOCH FROM date '2014-04-15' + interval '1 day')
    AND id = 123

留言

ERROR:  operator does not exist: text >= double precision
LINE 3: WHERE data->>'Datetime' BETWEEN

我做错了什么,请云有人帮助我吗?谢谢

->> 运算符 returns 一个 JSON 对象字段作为 text(参见 here)。你需要施放它:

SELECT *
FROM trips
WHERE (data->>'Datetime')::int 
  BETWEEN EXTRACT(EPOCH FROM date '2014-04-01') 
      AND EXTRACT(EPOCH FROM date '2014-04-15' + interval '1 day')
  AND id = 123