I’ve got the next problem up from this one: Comparing date ranges
The solution to comparing two ranges is the query:
SELECT * FROM periods WHERE NOT (range_start > @check_period_end OR range_end < @check_period_start)
I have the added problem. I am allowing people to enter a range of periods. To be precise they enter a duration (i.e 1 week) and a range of start dates (i.e. first 2 weeks in may) and I have to find out if there is a one week slot in the range they specified.
The naive solution is to run the above query for every day in my range. So – to check for 3 days slots in a month range I’d have to run 30 queries. Is there a more efficient way?
For bonus points – I am using Django. Is there a good solution using the Django ORM?
Edit – In an effort to simplify the question I think I’ve turned it into a different question! My actual problem is to find ‘free gaps’. I think this invalidates some of the ‘pure SQL’ approaches below. I thought it would be sensible to start a new question rather than muddling this one. Others are likely to find this question useful in it’s current form.
The problem is simpler than it may seem at first glance, as the user is not directly specifying an end date in their criteria.