【问题标题】:PostgreSQL OVERLAPS overator not inclusive of end time - RailsPostgreSQL OVERLAPS overator 不包括结束时间 - Rails
【发布时间】:2021-02-16 21:15:26
【问题描述】:

我在我的应用程序中使用 Rails 5 和 postgresql。

查询如下。

.where('(start_time, end_time) OVERLAPS (time without time zone ?, time without time zone ?)',
               start_time, end_time)

场景 1:

  • 范围 1 => 0:00 - 08:00

    范围 2 => 07:59 - 12:00

这表明重叠是正确的。

场景 2:

  • 范围 1 => 0:00 - 08:00

    范围 2 => 08:00 - 12:00

这不显示重叠。这是不正确的,因为 08:00 属于两个时间范围。

我认为问题在于 OVERLAPS 考虑的是

知道如何解决这个问题吗?

【问题讨论】:

    标签: ruby-on-rails postgresql datetime date-arithmetic


    【解决方案1】:

    The documentation 说得很清楚:

    每个时间段都被认为代表半开区间<em><strong>start</strong></em> &lt;= <em><strong>time</strong></em> &lt; <em><strong>end</strong></em>,除非<em><strong>start</strong></em><em><strong>end</strong></em> 相等,在这种情况下它代表单个时间瞬间。例如,这意味着只有一个共同端点的两个时间段不重叠。

    您可以使用范围类型和重叠运算符&amp;&amp;

    WHERE tsrange(start_time, end_time, '[]') && tsrange(?, ?, '[]')
    

    这里tsrange 的第三个参数指定包含两端。

    使用范围还有一个额外的优势,即您可以使用 GiST 索引来支持条件。

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 1970-01-01
      • 2011-05-29
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      相关资源
      最近更新 更多