MySQL查询查看常用时间间隔并显示间隔

MySQL query to check the common time interval and display the interval

我正在寻求有关以下问题的帮助。

我需要检查所有选定条目是否共享一个公共时间间隔,如果是,时间间隔是多少。

可视化问题:

id    openingTime          closingTime
1         09:00                18:00
2         11:00                15:00
3         12:00                20:00
4         21:00                23:00

期望的输出是得到一个空结果或一个具有重叠间隔的结果。

示例:

selected id    openingTime          closingTime
1,2 =>           11:00                15:00
1,2,3 =>         12:00                15:00
1,3 =>           12:00                18:00
1,2,3,4 =>       empty                empty

具有重叠间隔的 ID,SQL 命令很简单:

SELECT MAX(openingTime), MIN(closingTime) FROM table WHERE id IN (ids)

但是这个 SQL 查询不处理一个或多个条目不共享相同间隔的情况。

这里有一些示例数据,DB fiddle 可以试用一下:

CREATE TABLE `mytable` (
  `id` int(11) NOT NULL,
  `openingtime` time NOT NULL,
  `closingtime` time NOT NULL
);



INSERT INTO `mytable` (`id`, `openingtime`, `closingtime`) VALUES
(1, '09:00:00', '18:00:00'),
(2, '11:00:00', '15:00:00'),
(3, '12:00:00', '20:00:00'),
(4, '21:00:00', '23:00:00');

感谢您的帮助。

D.

我在考虑exists和聚合:

select min(openingtime), max(closingtime)
from (
    select t.*, 
        exists (
            select 1
            from mytable t1
            where t1.openingtime > t.closingtime or t1.closingtime < t.openingtime
        ) flag
    from mytable t
) t
having max(flag) = 0

子查询检查 table 中的任何其他行是否与当前行不重叠。然后外部查询聚合,如果有任何行被标记,则使用 having 过滤掉整个结果。

一个公共间隔将从开盘时间开始,到下一个闭盘时间结束。因此,您可以测试每个开始时间,计算重叠次数。

select o.time, min(t.closingtime)
from (select distinct time from t) o join
     t
     on o.time >= t.openingtime and o./time <= t.closingtime
group by o.openingtime
having count(*) = (select count(*) from t);

如果没有重叠,这 return 没有行。如果有多个周期,它 return 是所有重叠的周期(我认为每个 ID 一行是不可能的)。