【问题标题】:Query the Next Time Interval查询下一个时间间隔
【发布时间】:2013-01-03 12:43:48
【问题描述】:

我正在尝试从 mySQL 表中查询上限可用“时间范围”

+----+----------+---------+
| id | timefrom | timeto  | 
+----+----------+---------+
|  0 | 08:30    | 10:30   |
|  7 | 15:00    | 16:00   |
|  2 | 17:00    | 17:30   |
|  8 | 18:00    | 21:00   |
+----+----------+---------+

查询结果将是下一个可用时间范围,即 10:30 到 15:00

edit1: id 不在序列中

谢谢!

【问题讨论】:

  • 您如何确定“下一个可用时间范围”是“10:30 到 15:00”?
  • 该表实际上是一个每日时间段,从10:30到15:00的记录,表中没有显示其他条目,然后是下一个可用时间范围
  • 我不关注。 “16:00到17:00”和“17:30到18:00”不一样吗?
  • 是的,这就是我添加可用“时间范围”描述的原因
  • 表格中的间隔可能重叠吗?可能存在一个间隔与另一个完成的时间完全相同(如果是,是否返回零长度间隔或找到第一个非零间隔)?

标签: mysql datetime


【解决方案1】:

我认为你需要这个:

select t1.`timeto`, min(t2.`timefrom`)
from
  yourtable t1 inner join yourtable t2
  on t1.`timeto`<t2.`timefrom`
group by t1.`timeto`
having
  not exists (select null from yourtable t3
              where t1.`timeto`<t3.`timeto`
              and min(t2.`timefrom`)>t3.`timefrom`)

(仅当间隔不重叠时才有效)

【讨论】:

【解决方案2】:

我想我会使用类似的东西

SELECT
    t1.*,
    MIN(t2.`timefrom`) AS 'next (timefrom)',
    TIMEDIFF(MIN(t2.`timefrom`),t1.`timeto`) AS 'interval'
FROM `the_table` t1
LEFT OUTER JOIN `the_table` t2
ON t2.`timefrom` > t1.`timeto`
GROUP BY t1.`timefrom`,t1.`timeto`
#HAVING `next` IS NOT NULL

取消注释最后一行与在此处使用 INNER JOIN 而不是 LEFT OUTER JOIN 相同。我选择 LOJ 的原因是因为我想查看表中的所有记录,但这当然取决于您。

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 2019-01-22
    • 2011-11-09
    • 2023-02-21
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    相关资源
    最近更新 更多