Flamur Mavraj Flamur Mavraj - 2 months ago 5
SQL Question

SQL/Mysql Query available dates in database

I need some help querying my calendar/dates table

Scenario:
I have a "calendar" table with dates, user will set his available dates, usually day by day. So my table looks like this:

+------+------------+---------------------+---------------------+
| ID | user_id | start_date | end_date |
+------+------------+---------------------+---------------------+
| 1 | 1 | 2016-09-01 08:00:00 | 2016-09-01 16:00:00 |
| 2 | 1 | 2016-09-03 08:00:00 | 2016-09-03 16:00:00 |
| 3 | 1 | 2016-09-04 08:00:00 | 2016-09-04 16:00:00 |
| 3 | 1 | 2016-09-05 08:00:00 | 2016-09-05 16:00:00 |
+------+------------+---------------------+---------------------+


This means user 1 is available on the 1st, 3rd, 4th and 5th.

Lets say I want to query the table and find if user is available from date 2016-09-01 08:00:00 to 2016-09-05 16:00:00, this query must return zero rows since the user is not available on the 2nd of September. But if query from date 2016-09-03 08:00:00 to 2016-09-05 16:00: 00 then it will return these 3 rows.

Hope someone can help me with this

Answer

This could be one way (for a single user).

Note @endDate and @startDate are the supplied date fields to search.

SELECT 
*
FROM your_table 
WHERE EXISTS (
    SELECT 
    user_id
    FROM your_table 
    WHERE start_date >= @startDate 
    AND start_date <= @endDate
    AND user_id = 1
    GROUP BY user_id 
    HAVING SUM((DATEDIFF(end_date,start_date)+1)) = DATEDIFF(@endDate,@startDate)+1
)
AND start_date >= @startDate 
AND start_date <= @endDate
AND user_id = 1