我试图从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不按顺序
谢谢!
答案 0 :(得分: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`)
(仅当间隔不重叠时才会起作用)
答案 1 :(得分: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
取消注释最后一行与使用INNER JOIN
而不是LEFT OUTER JOIN
相同。我选择LOJ的原因是因为我想看表中的所有记录,但当然这取决于你。