我正在尝试使用 Postgresql 数据库在 Java Spring 上的时间戳间隔内检索数据。 我正在使用的查询之一运行良好(它返回过去 24 小时的数据):
@Query(value = "SELECT timestamp,lettura,stato FROM dati_impianti
WHERE sigla_impianto = :impianto and timestamp > now() - interval '24 hours'
ORDER BY timestamp DESC", nativeQuery = true)
List<ReadingEntity> findLastDay(@Param("impianto") String s);
但是,当我尝试返回具有不同时间戳的数据时,我收到 PSQL 异常:
@Query(value = "SELECT timestamp,lettura,stato FROM dati_impianti
WHERE sigla_impianto = :impianto and timestamp > :timestamp - interval '24 hours'
ORDER BY timestamp DESC", nativeQuery = true)
List<ReadingEntity> findDate(@Param("impianto") String s, @Param("timestamp") Timestamp t);
这是我遇到的异常:
org.postgresql.util.PSQLException: ERROR: operator does not exist: timestamp without time zone > interval
No operator matches the given name and argument types. You might need to add explicit type casts.
我无法理解的是,根据 PostgreSQL 文档,时间戳 - 间隔应该返回另一个时间戳。然而,从我的查询来看,我似乎正在将时间戳(来自表)与间隔进行比较,这是错误的。如果我尝试直接使用我的时间戳参数(以 timestamp > :timestamp 的形式,而不将其减少一个时间间隔),它可以工作,但不是我想要的。
我还尝试使用 :timestamp::timestamp 进行显式强制转换,但这似乎会由于 Spring 及其处理参数的方式而产生另一种错误。
最佳答案
您可能想尝试将参数显式转换为时间戳
:
where
sigla_impianto = :impianto
and timestamp > :timestamp::timestamp - interval '24 hours'
或者,可能:
where
sigla_impianto = :impianto
and timestamp > cast(:timestamp as timestamp) - interval '24 hours'
关于带时间戳返回间隔的 Java Spring/PgSQL 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60598586/