使用 Scala Slick 从 SQL 数据库中检索所有记录,其中时间戳列的日期在上个月或上周

Using Scala Slick retrieve all records from SQL db where date from timestamp column falls in the last month or last week

SQL 数据库中的时间戳是 datetime 类型,值以 2020-05-10T10:58:38.559Z 格式存储。我必须从 SQL 数据库中检索所有记录,其中时间戳列的日期落在上个月或上周。

作为 slick 的新手,我无法找到执行此操作的方法。

首先,您必须确保具有 java.time/joda.time 数据类型的映射。它们已在 other answers.

中描述

一旦您在 Slick 中定义了支持数据类型的 table,您就可以执行以下操作:

// depends on your domain's definition of "last month"
val beginningOfLastMonth: Instant = ...
val endingOfLastMonth: Instant = ...

tableQuery.filter { row =>
  row.timestamp >= beginningOfLastMonth &&
    row.timestamp <= endingOfLastMonth
}
.result

计算出 "last month" 和 "last week" 后,您就可以使用此范围比较来构建查询,该查询将为它们 return 所有结果。