Selecting entries by date - >= NOW(), MySQL

前端 未结 6 1061
盖世英雄少女心
盖世英雄少女心 2020-12-13 14:11

I have a Calendar of Events table and I would like to select events with dates equal to or greater than today. When I use the following SELECT statement, it only retrieves e

相关标签:
6条回答
  • 2020-12-13 14:24

    You are looking for CURDATE():

    $db->query("SELECT * FROM events WHERE event_date >= CURDATE()");
    

    Or:

    $db->query("SELECT * FROM events WHERE event_date >= CURRENT_DATE()");
    
    0 讨论(0)
  • 2020-12-13 14:38

    Here's the difference between CURDATE and NOW:

    mysql> select CURDATE();
    +------------+
    | CURDATE()  |
    +------------+
    | 2017-03-17 |
    +------------+
    1 row in set (0.03 sec)
    
    mysql> select NOW();
    +---------------------+
    | NOW()               |
    +---------------------+
    | 2017-03-17 09:04:45 |
    +---------------------+
    1 row in set (0.00 sec)
    

    I always use NOW just to be accurate

    0 讨论(0)
  • 2020-12-13 14:40

    If you care only about the date, not the time, use CURDATE() instead of NOW().

    Of course you can alternatively use the synonym CURRENT_DATE (with or without parentheses after it), but the docs I pointed to give CURDATE as the first spelling;-).

    0 讨论(0)
  • 2020-12-13 14:48

    The reason that this query:

    SELECT * FROM events WHERE event_date >= NOW()
    

    ...returns records from the future, is because NOW() includes the time as well as the date. And that time portion indicates the time at which the [function or triggering] statement began to execute. So that means the start of the day in a DATETIME data type looks like: 2010-06-24 00:00:00 (YYYY-MM-DD HH:MM:SS, to microsecond precision), which NOW() would show something like 2010-06-24 14:24:31...

    Here are your options:

    SELECT * FROM events WHERE event_date >= DATE(NOW())
    SELECT * FROM events WHERE event_date >= DATE(CURRENT_TIMESTAMP)
    SELECT * FROM events WHERE event_date >= CURRENT_DATE()
    SELECT * FROM events WHERE event_date >= CURRDATE()
    
    0 讨论(0)
  • 2020-12-13 14:48

    Your issue is that now() is very accurate. So dates for today and before now because they started at the beginning of the day.

    Use this:

    select * from events where datediff(event_date, now()) >= 0;
    
    0 讨论(0)
  • 2020-12-13 14:50

    You could also do

    <?php    
    $db->query("SELECT * FROM events WHERE UNIX_TIMESTAMP(event_date) >=     UNIX_TIMESTAMP(NOW())");
    ?>
    

    Which is more accurate than using CURTIME() if by any chance your using time as well as date

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