【问题标题】:Postgres/Knex How to get all entries where two timestamps contain a specified time period between themPostgres / Knex如何获取两个时间戳之间包含指定时间段的所有条目
【发布时间】:2018-01-13 15:35:33
【问题描述】:

我正在使用 Postgres 数据库构建一个应用程序,其中涉及比较时间表。我正在使用 knex 将其连接到节点;但如果解决方案最好由原始查询提供,我也可以走这条路。

我有一个名为"Schedules" 的表,其中包含一个"from_time" 和一个"to_time"

我希望能够给数据库一个"start_time""end_time" 并找到:

  1. 可以包含"start_time" 和“end_time”(即from_time <= start_time && end_time >= to_time)的所有计划
  2. "start_time""end_time" 重叠的所有计划(即, (start_time <= from_time && end_time > from_time) || (start_time < to_time && end_time >= from_time))

我考虑的一个可能的解决方案是将值简单地存储为 Unix 纪元中的整数......这是我的备份计划。但是,由于这些确实是时间值,因此最好将它们保留为时间戳值格式。

【问题讨论】:

  • from_timeto_time 代表 timestamps 还是 times?如果它们确实代表时间,那么跨越 00:00 时间是否有意义? (即:时间表从 22:00 开始,到次日 02:00 结束)。
  • 当你得到结果时:你需要区分overlapsis contained in(这只是overlaps的一个特例)?
  • 看看dbfiddle.uk/…,这是你要找的吗?
  • 你能澄清一下问题是什么吗?我不太明白你想在这里找到什么。

标签: node.js postgresql timestamp knex.js timestamp-with-timezone


【解决方案1】:

这是你的第一个条件

knex.select('*').from('Schedules').where('from_time', '<=', start_time).where('to_time', '<=', end_time)

这是给你的第二个

knex.select('*').from('Schedules').where(function () {
    this.where('from_time', '>=', start_time).where('from_time' ,'<', end_time))
}).orWhere(function () {
    this.where('to_time', '>', start_time).where('from_time' ,'<=', end_time))
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2022-06-12
    • 2021-07-31
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多