views:

348

answers:

1

This table is used to store sessions

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 TRUE
  AND ("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 practice way to get that ?

+2  A: 

I had such a query with a calendar application I once wrote. I think I used something like this:

... WHERE new_start < existing_end AND new_end > existing_start;

UPDATE This should definitely work ((ns, ne, es, ee) = (new_start, new_end, existing_start, existing_end)):

  1. ns - ne - es - ee: doesn't overlap and doesn't match (because ne < es)
  2. ns - es - ne - ee: ovarlaps and matches
  3. es - ns - ee - ne: ovarlaps and matches
  4. es - ee - ns - ne: doesn't overlap and doesn't match (because ns > ee)
  5. es - ns - ne - ee: ovarlaps and matches
  6. ns - es - ee - ne: ovarlaps and matches
soulmerge
Yes I saw this solution in a previous thread.But the case of [new] wrapping the [existing] is not covered.
Glide
@Glide: I think it should work, updated answer
soulmerge
You are right, this is clever, thx
Glide