2

我试图从 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 不在序列中

谢谢!

4

2 回答 2

2

我认为你需要这个:

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`)

(这只有在间隔不重叠时才有效)

于 2013-01-03T13:25:42.567 回答
1

我想我会使用类似的东西

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

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

于 2013-01-03T14:00:43.170 回答