2

Sorry if this question is basic, I am learning MySQL.

Let's assume I have one table with names and given dates:

+----+-----------+-----------+
|Name|StartDate  |EndDate    |
+----+-----------+-----------+
|A   |2013-08-29 |2014-12-29 |
|A   |2013-08-29 |2013-09-31 |
|B   |2015-01-02 |2015-03-20 |
|B   |2013-08-20 |2013-08-30 |
+----+-----------+-----------+

I would like to find the elements (Name) which has conflicting (overlapping) dates. Here, A has conflicting dates, B does not have, and code should return A. The overlapping between A and B does not matter. Thank you.

gurluk
  • 195
  • 2
  • 7

1 Answers1

0

You can do this with

select distinct name
from onetable t
where exists (select 1
              from onetable t2
              where t2.name = t.name and
                    t2.startdate < t.enddate and
                    t2.enddate > t.startdate
             );

The answer is similar to the previous answer, with the addition of the name comparison in the where clause.

The index that you want for this query is on table(name, startdate, enddate).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786