使用date_format选择日期范围MySQL

时间:2012-10-16 08:41:21

标签: mysql date date-format

我在使用MySQL选择日期范围时遇到了问题。

SELECT MvtDate,date_format(MvtDate,'%d-%m-%Y')
  FROM (`immmvt`)
 WHERE date_format(MvtDate,'%d-%m-%Y') BETWEEN '01-01-2010' AND '02-01-2010'

mvtDate类型的日期类似于2010-01-01 00:00:00

当我运行查询时,结果适用于日期和月份,但它也会显示其他年份的其他结果。

01-01-2011

2 个答案:

答案 0 :(得分:12)

您应该使用STR_TO_DATE,因为您想将string转换回date

SELECT MvtDate, date_format(MvtDate,'%d-%m-%Y')
FROM  `immmvt`
WHERE MvtDate BETWEEN STR_TO_DATE('01-01-2010','%d-%m-%Y') AND 
                      STR_TO_DATE('02-01-2010','%d-%m-%Y')
FYI: DATE_FORMAT() converts date to formatted string representation.
     STR_TO_DATE() converts formatted string back to date

答案 1 :(得分:1)

SELECT MvtDate,date_format(MvtDate,'%d-%m-%Y')
  FROM (`immmvt`)
 WHERE date_format(MvtDate,'%d-%m-%Y') IN ('01-01-2010', '02-01-2010')