Postgresql: Query Between time range using jsonb field

爷,独闯天下 提交于 2019-12-10 15:24:17

问题


I have a table with two fields:

id(serial), data(jsonb)

And into data I have records with a Datetime field stored as UNIX timestamps:

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

I'm trying to query between ranges:

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

Message

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

Something I'm doing wrong, please cloud somebody help me? Thanks.


回答1:


The ->> operator returns an JSON object field as text (see here). You need to cast it :

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


来源:https://stackoverflow.com/questions/30836025/postgresql-query-between-time-range-using-jsonb-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!