简体   繁体   中英

MySQL date comparisons returning different results

I have a query selecting rows between dates.

SELECT * FROM `table` WHERE statusDate >= '2014-10-01' AND statusDate <= '2014-10-31'

When I use the above query it returns significantly less rows than the following query...

SELECT * FROM `table` WHERE statusDate > '2014-09-30' AND statusDate < '2014-11-01'

Technically I'd have thought it would return the same results but it's not.

My understanding on the bottom query is that it selects from dates above and below the dates stated, not including. Why would the results be different?

If statusDate is a DATETIME column, the time of day will cause the results to be different for rows on the last day of the month. When you convert the date 2014-10-31 to a DATETIME , it's 2014-10-31 00:00:00 . If there's a row whose statusDate is 2014-10-31 09:23:11 , it will not be selected by the first query, but it will be selected by the second query.

You can solve this by using:

WHERE statusDate >= '2014-10-01' AND DATE(statusDate) <= '2014-10-31'

or you can add the time to the WHER clause:

WHERE statusDate >= '2014-10-01' AND statusDate <= '2014-10-31 23:59:59'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM