首页 > 解决方案 > 查询以显示今天在 postgres 中输入的记录(纪元时间)

问题描述

我有一个表,其列如下:

                                                       Table "public.myapp_table1"
   Column   |          Type          |                          Modifiers                           | Storage  | Stats target | Description 
------------+------------------------+--------------------------------------------------------------+----------+--------------+-------------
 id         | integer                | not null default nextval('myapp_database1_id_seq'::regclass) | plain    |              | 
 model_name | character varying(150) | not null                                                     | extended |              | 
 device_id  | character varying(150) | not null                                                     | extended |              | 
 data       | jsonb                  | not null                                                     | extended |              | 

在 json 字段数据中,有“时间戳”,其中时间以纪元格式存储(请参阅https://www.epochconverter.com/

我想显示今天输入的所有行。

我正在尝试查询:(查询json数据时有点新意)

select distinct(device_id) from myapp_table1 where (data->'timestamp')> 1570077000;

其中 1570077000 是今天从上午 10:00 开始的纪元时间。

我得到的错误是:

ERROR:  operator does not exist: jsonb > integer
LINE 1: ...ce_id) from myapp_table1 where (data->'timestamp')> 15700770...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

不知道如何管理那个“>”标志。还没有掌握文档。

如何解决这个问题?

标签: sqljsonpostgresql

解决方案


您需要使用->>以文本形式获取 JSON 值,而不是->返回 json 对象。此外,可能需要将文本值转换为(大)整数。

考虑:

where (data->>'timestamp')::bigint > 1570077000

参考:JSON 函数和运算符


推荐阅读