I need to check if two dates over lap with another two dates in my database.
My database looks like this
+----+--------------+------------+------------+
This is an old thread, but use BETWEEN. This is an excerpt from my timeclock, pls modify to your needs...
$qs = "SELECT COUNT(*) AS `count` FROM `timeclock` WHERE `userid` = :userid
AND (
(`timein` BETWEEN :timein AND :timeout OR `timeout` BETWEEN :timein AND :timeout )
OR
(:timein BETWEEN `timein` AND `timeout` OR :timeout BETWEEN `timein` AND `timeout`)
);";
This is just the where clause. Given InputStartDate and InputEndDate are given by user input, and DataStartDate and DataEndDate are the datetime values in the table:
where ((DataEndDate > InputStartDate) and (DataStartDate < InputEndDate))
I believe the following condition matches every possible overlapping case.
WHERE
(
(ScopeStartDate <= EndDate AND ScopeEndDate >= StartDate)
)
except if you declare illogic timespans (for example, those which end before starting)
You can cover all date overlapping cases even also when toDate
in database can possibly be null as follows:
SELECT * FROM `tableName` t
WHERE t.`startDate` <= $toDate
AND (t.`endDate` IS NULL OR t.`endDate` >= $startDate);
This will return all records that overlaps with the new start/end dates in anyway.