【问题标题】:Rails querying across midnight with time only columnRails 在午夜查询只有时间的列
【发布时间】:2020-12-15 07:49:44
【问题描述】:

我使用的是 Rails 6.0.2 和 MySQl 5.7 版。

在 camera_events 表上,我有一个 start_time 和一个 end_time 列,它们都是 time 数据类型,因为我不需要日期,我只需要知道事件何时开始和何时结束。

我正在尝试查询表以获取在 start_time 和 end_time 之间的所有事件。问题是任何时间跨度跨越 midnight 或将其 end_time 设置为 midnight 的事件,因为它在数据库中记录为 00:00。

我的问题是尝试查找介于特定时间(例如 22:00 和 02:00)之间的任何事件。

【问题讨论】:

标签: mysql ruby-on-rails time range-query


【解决方案1】:

今天凌晨 2 点,我有了一个想法,并且实际上解决了我的问题。我必须这样做的方法是将查询分解为带有 or 的 2 个 where 语句。基本上我正在做的是检查 end_time 是否大于 start_time (对于整个像 01:00 到 10:00)以及 end_time 小于 start_time 的地方(这意味着 end_time 跨越午夜像 22 :00 到 02:00)。

  def time_span_search(current_time)
    CameraEvent
        .where('end_time > start_time and start_time <= ? and end_time >= ?', current_time, current_time)
        .or(
            CameraEvent
                .where('end_time <= start_time and start_time <= ? and start_time <= ? and end_time >= ? and end_time <= ?', current_time, '23:59', '00:00', current_time) )
        .pluck(:id)
  end

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 2012-09-25
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多