Pergunta

Hi I was wondering why this statement is working in mySQL

SELECT COUNT(*) AS `numrows` 
FROM (`myTable`) 
WHERE DATE_FORMAT(creationDateTime, '%m/%d/%Y') BETWEEN '02/21/2011' AND '03/20/2011'

but this is not

SELECT COUNT(*) AS `numrows` 
FROM (`myTable`) 
WHERE DATE_FORMAT(creationDateTime, '%m/%d/%Y') BETWEEN '12/21/2010' AND '03/20/2011'

The first statement returns 'xx' count of the number of rows while the second one returns '0'

The only difference I see is that the "from" date is in 2010 and the "end" date is in 2011. To test if this was the problem I queried from '12/31/2010' and it still gave me 0 results but when I set the start date as '01/01/2011' it gave me the number of records that were created in that time span.

Is there something I am missing with regards to mySQL's BETWEEN and using dates from different years?

Thanks for the help!

Foi útil?

Solução

DATE_FORMAT() returns a string, not a date. By using it you're forcing a string comparison instead of a date comparison. You should omit the DATE_FORMAT and use YYYY-MM-DD date strings instead.

Outras dicas

Try using the date format BETWEEN '2010-12-21' AND '2011-03-20'. Also remove the DATE_FORMAT() function.

So, this:

SELECT COUNT(*) AS `numrows` 
FROM `myTable` 
WHERE creationDateTime BETWEEN '2010-12-21' AND '2011-03-20'
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top