Finding 'free' times in MySQL

Posted by James Inman on Stack Overflow See other posts from Stack Overflow or by James Inman
Published on 2010-05-09T16:07:56Z Indexed on 2010/05/09 16:08 UTC
Read the original article Hit count: 165

Filed under:
|
|

Hi,

I've got a table as follows:

mysql> DESCRIBE student_lectures;
+------------------+----------+------+-----+---------+----------------+
| Field            | Type     | Null | Key | Default | Extra          |
+------------------+----------+------+-----+---------+----------------+
| id               | int(11)  | NO   | PRI | NULL    | auto_increment |
| course_module_id | int(11)  | YES  | MUL | NULL    |                |
| day              | int(11)  | YES  |     | NULL    |                |
| start            | datetime | YES  |     | NULL    |                |
| end              | datetime | YES  |     | NULL    |                |
| cancelled_at     | datetime | YES  |     | NULL    |                |
| lecture_type_id  | int(11)  | YES  |     | NULL    |                |
| lecture_id       | int(11)  | YES  |     | NULL    |                |
| student_id       | int(11)  | YES  |     | NULL    |                |
| created_at       | datetime | YES  |     | NULL    |                |
| updated_at       | datetime | YES  |     | NULL    |                |
+------------------+----------+------+-----+---------+----------------+

I'm essentially wanting to find times when a lecture doesn't happen - so to do this I'm thinking a query to group overlapping lectures together (so, for example, 9am-10am and 10am-11am lectures will be shown as a single 9am-11am lecture). There may be more than two lectures back-to-back.

I've currently got this:

SELECT l.start, l2.end
FROM student_lectures l
LEFT JOIN student_lectures l2 ON ( l2.start = l.end )
WHERE l.student_id = 1 AND l.start >= '2010-04-26 09:00:00' AND l.end <= '2010-04-30 19:00:00' AND l2.end IS NOT NULL AND l2.end != l.start
GROUP BY l.start, l2.end
ORDER BY l.start, l2.start

Which returns:

+---------------------+---------------------+
| start               | end                 |
+---------------------+---------------------+
| 2010-04-26 09:00:00 | 2010-04-26 11:00:00 |
| 2010-04-26 10:00:00 | 2010-04-26 12:00:00 |
| 2010-04-26 10:00:00 | 2010-04-26 13:00:00 |
| 2010-04-26 13:15:00 | 2010-04-26 16:15:00 |
| 2010-04-26 14:15:00 | 2010-04-26 16:15:00 |
| 2010-04-26 15:15:00 | 2010-04-26 17:15:00 |
| 2010-04-26 16:15:00 | 2010-04-26 18:15:00 |
...etc...

The output I'm looking for from this would be:

+---------------------+---------------------+
| start               | end                 |
+---------------------+---------------------+
| 2010-04-26 09:00:00 | 2010-04-26 13:00:00 |
| 2010-04-26 13:15:00 | 2010-04-26 18:15:00 |

Any help appreciated, thanks!

© Stack Overflow or respective owner

Related posts about mysql

Related posts about dates