Search code examples
phpmysqlsqldatetimesubquery

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


I´m looking for some help with the following problem.

I need to check, whether all selected entries share a common time interval and if so, what is the time interval.

To visualize the problem:

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

Desired output is to get either an empty result or one result with the overlapping interval.

Examples:

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

Having IDs with overlapping intervals, the SQL command is easy:

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

But this SQL query doesn't deal with the cases when one or more entries are not sharing the same interval.

Here is some sample data and DB fiddle to try it out:

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');

Thank you for your help.

D.


Solution

  • I am thinking exists and aggregation:

    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
    

    The subquery checks if any other row in the table does not overlap with the current row. Then the outer query aggregates, and uses having to filter out the whole result if any row was flagged.