jeudi 24 novembre 2016

SQL/Mysql query available dates and times in database

I need some help querying my calendar/dates table

Scenario: I have a "calendar" table with dates and times (see below), users will set their available dates, usually day by day with available time slots for each 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 00:00:00 | 2016-09-03 23:59:59 | 
|    3 |          1 | 2016-09-04 00:00:00 | 2016-09-04 16:00:00 | 
|    4 |          1 | 2016-09-05 08:00:00 | 2016-09-05 16:00:00 | 
|    5 |          2 | 2016-09-05 08:00:00 | 2016-09-05 16:00:00 | 
|    6 |          2 | 2016-09-07 08:00:00 | 2016-09-07 16:00:00 | 
|    7 |          2 | 2016-09-08 08:00:00 | 2016-09-08 16:00:00 | 
|    8 |          2 | 2016-09-08 18:00:00 | 2016-09-08 22:00:00 |
+------+------------+---------------------+---------------------+ 

We have 2 users here so I want the following:

  • If I search for start_date = 2016-09-05 08:00:00 and end_date = 2016-09-05 16:00:00 it should return user 1 and 2. Since both of them has an entry with these dates. Same goes as well if start_date = 2016-09-05 09:00:00 and end_date = 2016-09-05 15:00:00, this should as well return both users since the time im searching for is between the time slots as shown in the example.

  • Second scenario is a little bit more tricky, If user search for start_date = 2016-09-03 08:00:00 and end_date = 2016-09-04 16:00:00 i want the query to check the following: see if the user is available each day at these times, so in this case, is the user available on 2016-09-03 between 08:00:00 and 16:00:00 and as well on 2016-09-04 between 08:00:00 and 16:00:00. In the example over this should return user 1.

Im open for suggestion on re-designed my schema if needed.

Hope some can help me with this.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire