phpSimon;10987983 wrote:
I can find out when the next available date that ALL items are NOT booked by doing something like this
That's not at all what you are doing. You are selecting the end dates for all bookings, which tells you absolutely nothing about when things are NOT booked. Well almost nothing. You do know that after the last end date, no items are booked, but that is not finding the next date (which happens to be the earliest date) when nothing is booked, that is finding the last such date.
Unless I'm misstaken, you'd need to recursively expand any period (start-end) with any overlapping period, until you have no more overlapping peroids, and from that take the first date outside of those periods.
For example, let's say you have bookings in the same month
1-3, 2-3, 2-5, 3-5, 4-6
8-10, 8-13, 12-14, 9-15
20-21, 21-23, 22-31
These rows would be "period-exapnded" to
1-6
8-15
20-31
which yields the answer 7. The same data structure would also be able to answer the question of what blocks of certain number of days exist.
But, if you only want to find out if a particular date cotains no bookings at all, that is a whole lot easier
SELECT COUNT(*) AS rows FROM bookings WHERE @some_date NOT BETWEEN start_date AND end_date
0 rows = no items booked that date. rows > 0, 1 or more items booked that date.
And the same goes for finding out if a particular date is within a block of free days
SELECT COUNT(*) AS rows FROM bookings WHERE
-- first day in the period can't be within some booking period
(@period_start NOT BETWEEN start_date AND end_date)
AND
-- same goes for last day in the period
(@period_end NOT BETWEEN start_date AND end_date)
AND
-- all days in between also can't be inside a booked period
(@period_start > end_date OR @period_end < start_date)