SQL between dates including start and end dates

后端 未结 6 821
野性不改
野性不改 2021-01-04 08:34

So I have this:

 (CURDATE() BETWEEN start_date AND end_date) 

Works fine.

But when the CURDATE() is 2011-12-02 and th

相关标签:
6条回答
  • 2021-01-04 09:11

    It will work ... BETWEEN works inclusive of the boundary values. That is,

    (CURDATE() BETWEEN start_date AND end_date)
    

    including start_date,end_date and any day falling between

    CURDATE() BETWEEN start_date AND ADDDATE(CURDATE(), INTERVAL 1 DAY);
    
    0 讨论(0)
  • 2021-01-04 09:16

    cast (end_date - Start_date as double precision) * 86400

    0 讨论(0)
  • 2021-01-04 09:24

    Maybe the answer to this question refers to a bug in an old version of MySql because between is inclusive, which means it will grab rows between the start and end dates inclusive, not just between the start and one day before the end.

    Try this:

    SELECT CURDATE() BETWEEN CURDATE() AND CURDATE();
    

    The result is 1 (i.e. true). I believe the original poster problem lies with mixing up proper dates (DATE) and dates with time (DATETIME or TIMESTAMP).

    Try this:

    SELECT NOW() BETWEEN CURDATE() AND CURDATE();
    SELECT NOW() BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY);
    

    The result is 0 for the first select and 1 for the second. What happened is a DATE is equivalent to a DATETIME with zero time so unless NOW() is called exactly at midnight it will be greater than CURDATE() and fall outside of the BETWEEN statement. To prevent this test only the DATE part of a DATETIME using the DATE() function:

    SELECT DATE(NOW()) BETWEEN CURDATE() AND CURDATE();
    
    0 讨论(0)
  • 2021-01-04 09:25

    Use start_date <= CURDATE() AND end_date > CURDATE()

    0 讨论(0)
  • 2021-01-04 09:31

    Since both columns are timestamps, you need to make sure times don't trip you up. To keep the times from tripping you up, cast the timestamps to date.

    where current_date between cast(start_date as date) 
                           and cast(end_date as date);
    
    0 讨论(0)
  • 2021-01-04 09:32

    Well, you could try

    CURDATE() BETWEEN start_date AND DATE_ADD(end_date, INTERVAL 1 DAY)
    
    0 讨论(0)
提交回复
热议问题