I have a table availablities which holds availabilities of users:
row_id | user_id | available_from | available_to
-------------------------------------------------------------
1 | 1 | 2012-02-01 08:00:00 | 2012-02-01 09:00:00
2 | 1 | 2012-02-01 09:00:00 | 2012-02-01 10:00:00
3 | 2 | 2012-02-01 08:00:00 | 2012-02-01 10:00:00
4 | 3 | 2012-02-01 07:00:00 | 2012-02-01 12:00:00
I need to get all available users from this table for a certain event.
Scenario: get all available users for an event that starts 2012-02-01 08:00:00 and ends 2012-02-01 10:00:00.
I have no problem getting user_ids (2,3):
SELECT `user_id` FROM `availablities`
WHERE `available_from` <= "2012-02-01 08:00:00"
AND `available_to` >= "2012-02-01 10:00:00"
I am having a hard time though to find a query that will also return user_id (1). For that the query must somehown combine the two rows (1) and (2) of user_id (1) because only the sum of those two availabilities fits the event.
In a perfect world the adjacent availabilities on the rows (1,2) would be in just one row. There are reasons why it is saved this ways and I can’t just “optimize” the data in the tables to combine adjacent availabilities in one row.
So what I need is a way in mysql to return user_ids (1,2,3) in one query for the given timeframe – possible or do I have to find another approach?
If you need to do this in one query you could try combining MySQL User Defined variables and some inline view trickery:
I took your test data on a bit and included a user (user_id = 4) who was available between 2012-02-01 08:00:00 and 2012-02-01 08:30:00 and then again between 2012-02-01 09:00:00 and 2012-02-01 10:00:00. So he was not available for the entire period between 2012-02-01 08:00:00 and 2012-02-01 10:00:00 (coffee break?!).
So the expected result is that user_id = 1 is returned for the time period but user_id =4 is not.
Here is the test I used: