I have a set of periods like:
CREATE TABLE `periods` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`start_at` date DEFAULT NULL,
`end_at` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
LOCK TABLES `periods` WRITE;
INSERT INTO `periods` (`id`, `start_at`, `end_at`)
VALUES
(1,'2013-04-29','2013-04-30'),
(2,'2013-05-05','2013-05-10'),
(3,'2013-05-10','2013-05-15'),
(4,'2013-05-15','2013-05-16'),
(5,'2013-05-18','2013-05-19'),
(6,'2013-05-19','2013-05-25');
UNLOCK TABLES;
My intended desire, is the most optimized way to know if a given period is fully covered by one or multiple periods.
For instance:
1) to get null
for a request from 2013-04-29
until 2013-05-10
, cause no period covers from 2013-04=30
to 2013-05-05
2) to get the period ids (or at least true
or any content) for a request from 2013-05-06
to 2013-05-15
UPDATE: The main goal is to define if the given period (from 2013-05-06
to 2013-05-15
as per example 2) is rentable. The periods in database are available rental seasons, so if any of the day are not covered, the entire stay can not be rented.
This unfortunately only returns something, if there is a period covered.
EDIT: See here for a MySQL working SQL Fiddle: SQLFiddle, that actually works properly this time :-)
Try these. The bottom line is that if
Shortfall > 0
then you can't book the rental.MSSQL - this is how I worked it out
This provides output like this:
MySQL - this is what you actually want
You can do this all in one query. The following query assumes that you have
@StartDate
and@EndDate
defined.The key idea is that you only need to test for one day before a start date or one day after an end date. If there is a period with no coverage, then it will appear during this time. The following query calculates the test dates and whether they are aavailable:
This is more information than you need. You just want
0
in the first case and1
in the second case. This is just a test of whetherp.id
in the above query is everNULL
:This query might have an off-by-one error (depending on whether there is availability on the end date). Such a problem is easily fixed.
While I like the approach of @Dommer and the details included (thanks a lot for that) I prefer the approach contributed by @snoyes on IRC#mysql.
A working SQLFiddle is also available.
For more details, the initial reference comes from http://www.artfulsoftware.com/infotree/qrytip.php?id=577