PHP/MySQL SELECT
I have a table with available hours a specific day for a meeting room. The Temp_Res get the timestamp when a booking is ongoing (to lock those rows). I would like to get every possible time slot if meeting to be booked is 2 hours.
Day Hour Temp_Res
22 8 0000-00-00 00:00:00
22 9 0000-00-00 00:00:00
22 10 0000-00-00 00:00:00
22 11 2012-05-18 22:02:00
22 12 2012-05-18 22:02:00
22 13 2012-05-18 22:02:00
22 14 0000-00-00 00:00:00
22 15 0000-00-00 00:00:00
22 16 0000-00-00 00:00:00
22 17 0000-00-00 00:00:00
So, if the time slotneeded is 2 hours, only Hour 8, 9, 14, 15, 16 would be the output. (I would then use the hour and add 2 to get the slots: 8-10, 9-11, 14-16, 15-17 and 16-18)
If time slot is 3 hours, only Hour 8, 14, 15 would be the output and slots: 8-11, 14-17, 15-18….etc
To be able to do this in a SELECT (if possible) there must be a way of looking on the other rows in the table to determine if the specific row shall be included or not.
1. Is it possible to look on other rows and do this with a SELECT with WHERE (or similar)?
2. If possible, could you please guide me into the right direction?
3. Other solutions/ideas (except the ones below) are also very appreciated!
Otherwise I have to solve it by:
a) creating an extra time slot table
b) having an extra column stating the maximum time slot for that specific row, see below.
Day Hour Slot Temp_Res
22 8 3 0000-00-00 00:00:00
22 9 2 0000-00-00 00:00:00
22 10 1 0000-00-00 00:00:00
22 11 0 2012-05-18 22:02:00
22 12 0 2012-05-18 22:02:00
22 13 0 2012-05-18 22:02:00
22 14 4 0000-00-00 00:00:00
22 15 3 0000-00-00 00:00:00
22 16 2 0000-00-00 00:00:00
22 17 1 0000-00-00 00:00:00
SELECT Day, Hour FROM table
WHERE Slot>=2 AND Temp_Res<“2012-05-18 22:00:00”
GROUP BY Day, Hour
I would suggest using the start time and the meeting length to compute the end time, which is equivalent to “the last hour that needs to be free in order for this booking to occur.” You can then use an inner join to only select start times where every hour up to the end time is also unbooked. For a four-hour meeting, your query might look like this:
You can use a loop in PHP to add the required number of inner join clauses onto your query text (and because you’re using a variable you calculated yourself, you don’t have to worry about injection). It will always be (duration of meeting – 1).
This will return no open times if someone tries to schedule a meeting that would go across midnight, but if that’s undesired you can easily write logic to increment the day variable appropriately.