Are there any MySQL functions to get all rows with with a start or end date that fall between a given start and end date?

前端 未结 5 2270
名媛妹妹
名媛妹妹 2020-12-06 12:48

I have a table of events with a recorded start and end time as a MySQL DATETIME object (in the format YYYY-MM-DD HH:MM:SS. I want to find all events that occur

相关标签:
5条回答
  • 2020-12-06 13:10

    The answers by @Bill the Lizard and @Robert Gamble are correct for the question as asked, but I do wonder if you're asking what you think you are... If you're looking for overlapping events then you need to take into account events longer than your search range.

               Monday   Tuesday   Wednesday   Thursday
    
    Search:                |-----------|
    
    Shopping                       |-----|              Found OK
    Eating              |--------|                      Found OK
    Stack Overflow |---------------------------------|  Not found!
    

    If you wanted to include SO, you'd do:

    SELECT * FROM table WHERE (start_date < end_of_range AND end_date > start_of_range)

    0 讨论(0)
  • 2020-12-06 13:17

    This will find every event that is completely contained inside the range:

    SELECT * FROM table WHERE start_date BETWEEN start_of_range AND end_of_range 
                          AND stop_date  BETWEEN start_of_range AND end_of_range
    

    This will find any events where any part of the event overlaps any part of the range:

    SELECT * FROM table WHERE start_date <= end_of_range 
                          AND stop_date  >= start_of_range
    
    0 讨论(0)
  • 2020-12-06 13:21

    Basically, you can use regular comparisons -- the ones above should work -- the trick is to check all the different cases that can occur.

    A) events with an ending date within the range

    B) events with a starting date within the range

    C) events with both starting and ending dates within the range

    D) events with both starting and ending dates outside the range, but overlapping it

    Robert's answer is a good one, but it doesn't take into account case D, where the event starts before the range and ends after the range.

    0 讨论(0)
  • 2020-12-06 13:21

    Llya, Roberts answer with,

    SELECT * FROM table WHERE start_date <= end_of_range AND stop_date >= start_of_range

    works fine with,

    D) events with both starting and ending dates outside the range, but overlapping it

    ??

    0 讨论(0)
  • 2020-12-06 13:22
    SELECT *
    FROM table
    WHERE startdate >= 'starting date' AND startdate < 'ending date'
        OR enddate >= 'starting date' AND enddate < 'ending date'
    

    should work for you.

    Make sure you specify 'starting date' and 'ending date' with the time included.

    '2008-01-01 00:00:00'' AND '2008-01-31 23:59:59'
    

    This will help to avoid errors where dates are the same, but your time falls within the interval by a few hours, minutes, or seconds.

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