MySQL check if two date range overlap with input

前端 未结 4 740
生来不讨喜
生来不讨喜 2021-02-04 20:32

I need to check if two dates over lap with another two dates in my database.

My database looks like this

+----+--------------+------------+------------+
         


        
相关标签:
4条回答
  • 2021-02-04 21:01

    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`)
                        );";
    
    0 讨论(0)
  • 2021-02-04 21:04

    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))
    
    0 讨论(0)
  • 2021-02-04 21:08

    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)

    0 讨论(0)
  • 2021-02-04 21:10

    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.

    0 讨论(0)
提交回复
热议问题