Selecting date range MySQL with date_format

假如想象 提交于 2019-12-30 04:43:09

问题


I've got an issue selecting a date range with 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 type is date like 2010-01-01 00:00:00.

When I run the query, the result works for the days and the months but it also show me other result from other years.

Like 01-01-2011 etc.


回答1:


You should use STR_TO_DATE since you want to convert string back to 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



回答2:


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


来源:https://stackoverflow.com/questions/12910691/selecting-date-range-mysql-with-date-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!