I’m making a booking system in PHP/MySQL.
I want to be able to select a month, select a booking length, and find how many periods of the given length are available (ie, not marked as booked) within that month.
I started by creating a table of days, each day has a field that indicates if it’s reserved or not, as well as a date. The two tables are:
CREATE TABLE `day` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`booking` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE `booking` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start` date DEFAULT NULL,
`end` date DEFAULT NULL,
PRIMARY KEY (`id`)
)
So far I’ve been able to count how many days in a month aren’t booked – but that doesn’t necessarily tell me if say there are 7 days in a row:
SELECT
EXTRACT(YEAR FROM date) as year,
EXTRACT( MONTH FROM date) as month,
count(day.id)
FROM
day
WHERE booking IS NULL
GROUP BY year, month
At this point I’m considering loading all the days for my given month, and iterating through them in PHP to make up my numbers, but it seems kinda dumb and inefficient. Does anyone have a suggestion how I can find this information directly from MySQL?
Assuming you want ranges of at least 7 days in July, 2012, then:
will produce this output:
The clause
is used to include all ranges, even if the range extends into the previous, or next month. If you want ranges that fall exclusively in a single month, use:
See http://sqlfiddle.com/#!2/4e36a/4 for an interactive demo.