Finding free blocks of time in mysql and php?

Try this query

SELECT
  a.id,
  a.start_hour,
  a.end_hour,
  TIMEDIFF(la.start_hour, a.end_hour) as `Free Time`
FROM appointment as a
  LEFT JOIN(SELECT * FROM appointment LIMIT 1,18446744073709551615) AS la
    ON la.id = a.id + 1
  LEFT JOIN (SELECT * FROM appointment) AS ra ON a.id = ra.id

This will show these results

+---------------------------------------------+
¦ id ¦ start_hour BY ¦ end_hour   | Free Time |
¦----+---------------¦------------------------|
¦  1 ¦   08:00:00    ¦  08:15:00  | 05:45:00  |
¦  2 ¦   14:00:00    ¦  14:30:00  | 02:30:00  |
¦  3 ¦   17:00:00    ¦  17:45:00  | 03:15:00  |
¦  4 ¦   21:00:00    ¦  21:00:00  | (NULL)    |
+--------------------+------------------------+ 

Also you must have the 21:00:00 in the table or you wont be able to get the last time difference. i entered 21:00:00 as start and end date in the table.

EDITED

This is modified query

SELECT
  a.id,
  a.end_hour AS `Free time Start`,
  IFNULL(la.start_hour,a.end_hour) AS `Free Time End`,
  IFNULL(TIMEDIFF(la.start_hour, a.end_hour),'00:00:00') AS `Total Free Time`
FROM appointment AS a
  LEFT JOIN (SELECT * FROM appointment LIMIT 1,18446744073709551615) AS la
    ON la.id = (SELECT MIN(id) FROM appointment where id > a.id LIMIT 1)      

And the result is

+--------------------------------------------------------+
¦ id ¦ Free time Start ¦ Free Time End | Total Free Time |
¦----+-----------------¦---------------------------------|
¦  1 ¦   08:15:00      ¦ 14:00:00      |    05:45:00     |
¦  2 ¦   14:30:00      ¦ 17:00:00      |    02:30:00     |
¦  3 ¦   17:45:00      ¦ 21:00:00      |    03:15:00     |
¦  4 ¦   21:00:00      ¦ 21:00:00      |    00:00:00     |
+----------------------+---------------------------------+  

The points to learn from this query are

  1. Timediff function usage. timediff(‘end time’,’start time’)
  2. Joining with upper number
  3. Avoid first record in join with a long offset and limit starting from 1 instead of zero
  4. IFNULL usage ifnull(‘if here comes null’,’select this then’)

Leave a Comment