This table is used to store sessions (events):
CREATE TABLE session (
id int(11) NOT NULL AUTO_INCREMENT
, start_date date
, end_date date
);
INSERT INTO session
(start_date, end_date)
VALUES
("2010-01-01", "2010-01-10")
, ("2010-01-20", "2010-01-30")
, ("2010-02-01", "2010-02-15")
;
We don't want to have conflict between ranges.
Let's say we need to insert a new session from 2010-01-05 to 2010-01-25.
We would like to know the conflicting session(s).
Here is my query:
SELECT *
FROM session
WHERE "2010-01-05" BETWEEN start_date AND end_date
OR "2010-01-25" BETWEEN start_date AND end_date
OR "2010-01-05" >= start_date AND "2010-01-25" <= end_date
;
Here is the result:
+----+------------+------------+
| id | start_date | end_date |
+----+------------+------------+
| 1 | 2010-01-01 | 2010-01-10 |
| 2 | 2010-01-20 | 2010-01-30 |
+----+------------+------------+
Is there a better way to get that?
Recently I was struggling with the same issue and came to end with this one easy step (This may not be a good approach or memory consuming)-
This helped me find the entries with overlapping date ranges.
Hope this helps someone.
I had faced the similar problem. My problem was to stop booking between a range of blocked dates. For example booking is blocked for a property between 2nd may to 7th may. I needed to find any kind of overlapping date to detect and stop the booking. My solution is similar to LordJavac.
Let me know if it doesn't work.
Given two intervals like (s1, e1) and (s2, e2) with s1<e1 and s2<e2
You can calculate overlapping like this:
Will also work if one interval is within the other one.
I had such a query with a calendar application I once wrote. I think I used something like this:
UPDATE This should definitely work ((ns, ne, es, ee) = (new_start, new_end, existing_start, existing_end)):
Here is a fiddle
Lamy's answer is good, but you can optimize it a little more.
This will catch all four scenarios where the ranges overlap and exclude the two where they don't.
These 3 lines of sql clauses cover the 4 cases of overlapping required.