首页 > 解决方案 > 如何选择过去一小时内创建的所有行?

问题描述

我的查询是

SELECT  * FROM email_operation WHERE cdate = CURRENT_DATE  and ctime  >= (NOW() - INTERVAL '1 hour' )

选择在最后一小时创建的所有行,但它不起作用。它在>=

SELECT  * FROM email_operation WHERE cdate = CURRENT_DATE  and ctime  >= (NOW() - INTERVAL '12 hour' )
> ERROR:  operator does not exist: time without time zone >= timestamp with time zone
LINE 1: ..._operation WHERE cdate = CURRENT_DATE  and ctime  >= (NOW() ...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

> Time: 0.001s

标签: sqlpostgresql

解决方案


显然ctime是一time列,因此您无法将其与时间戳(这是错误消息告诉您的内容)进行比较。您需要current_time改用:

and ctime >= current_time - interval '1 hour'

请注意,这在午夜左右无法正常工作。

似乎您已将日期和时间分成两列(这是一个坏主意),但您可以将它们组合起来比较时间戳:

and cdate + ctime >= current_timestamp - interval '1 hour'

推荐阅读