MySQL - select data from database between two dates

后端 未结 8 1191
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 22:07

I have saved the dates of a user\'s registration as a datetime, so that\'s for instance 2011-12-06 10:45:36. I have run this query and I expected this item

相关标签:
8条回答
  • 2020-11-27 23:03

    You need to use '2011-12-07' as the end point as a date without a time default to time 00:00:00.

    So what you have actually written is interpreted as:

     SELECT users.* 
     FROM   users
     WHERE  created_at >= '2011-12-01 00:00:00' 
       AND  created_at <= '2011-12-06 00:00:00'
    

    And your time stamp is: 2011-12-06 10:45:36 which is not between those points.
    Change this too:

     SELECT users.* 
     FROM   users
     WHERE  created_at >= '2011-12-01'  -- Implied 00:00:00
       AND  created_at <  '2011-12-07'  -- Implied 00:00:00 and smaller than 
                                       --                  thus any time on 06
    
    0 讨论(0)
  • 2020-11-27 23:06

    Your problem is that the short version of dates uses midnight as the default. So your query is actually:

    SELECT users.* FROM users 
    WHERE created_at >= '2011-12-01 00:00:00' 
    AND created_at <= '2011-12-06 00:00:00'
    

    This is why you aren't seeing the record for 10:45.

    Change it to:

    SELECT users.* FROM users 
    WHERE created_at >= '2011-12-01' 
    AND created_at <= '2011-12-07'
    

    You can also use:

    SELECT users.* from users 
    WHERE created_at >= '2011-12-01' 
    AND created_at <= date_add('2011-12-01', INTERVAL 7 DAY)
    

    Which will select all users in the same interval you are looking for.

    You might also find the BETWEEN operator more readable:

    SELECT users.* from users 
    WHERE created_at BETWEEN('2011-12-01', date_add('2011-12-01', INTERVAL 7 DAY));
    
    0 讨论(0)
提交回复
热议问题