我正在使用Postgres数据库构建一个应用程序,这涉及比较时间表。我正在使用 knex 将其连接到节点;但是,如果解决方案最好由原始查询提供,我也可以走这条路。
我有一个名为"Schedules"
的表,其中包含一个"from_time"
和一个"to_time"
。
我希望能够给数据库一个"start_time"
和"end_time"
并找到:
- 可以包含
"start_time"
和"end_time"(即from_time <= start_time && end_time >= to_time
(的所有时间表 - 与
"start_time"
和"end_time"
重叠的所有时间表(即(start_time <= from_time && end_time > from_time) || (start_time < to_time && end_time >= from_time))
我考虑的一种可能的解决方案是简单地将值存储为 Unix 纪元中的整数......这是我的备份计划。 但是,由于这些确实是时间值,因此最好将它们保留为时间戳值格式。
这是针对您的第一个条件
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))
})