mySQL dateTime range Query Issue

后端 未结 3 2131
时光说笑
时光说笑 2021-02-01 15:43

I have a quick question. I\'m have a db an audit Table with a datetime column in it. (i.e 2012-03-27 00:00:00) and I\'m building a mySQL query to return a set of rows if the dat

相关标签:
3条回答
  • 2021-02-01 15:53

    As far as I know, dates in MySql are represented with the format yyyy-MM-dd hh:mm:ss hence you need to do this:

    SELECT * FROM util_audit 
    WHERE DATED >= '2012-02-15 00:00:00' AND DATED <= '2012-03-31 00:00:00';
    

    Or even better:

    SELECT * FROM util_audit 
    WHERE DATED BETWEEN '2012-02-15 00:00:00' AND '2012-03-31 00:00:00';
    
    0 讨论(0)
  • 2021-02-01 16:07

    Try:

    SELECT * FROM util_audit WHERE `DATED` BETWEEN "2012-03-15" AND "2012-03-31";
    
    0 讨论(0)
  • 2021-02-01 16:13

    There's a few edge cases which need to be caught here by using the correct end date, if not items on the 31st are ignored:

    SELECT * FROM util_audit 
    WHERE DATED >= '2012-02-15 00:00:00' AND DATED <= '2012-03-31 23:59:59';
    
    SELECT * FROM util_audit 
    WHERE DATED BETWEEN '2012-02-15 00:00:00' AND '2012-03-31 23:59:59';
    

    Or you could push the end date forward and use:

    SELECT * FROM util_audit 
    WHERE DATED >= '2012-02-15 00:00:00' AND DATED < '2012-04-01';
    
    SELECT * FROM util_audit 
    WHERE DATED BETWEEN '2012-02-15 00:00:00' AND '2012-04-01';
    

    Just came across this myself so hope it helps if other people find this page.

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