Query varchar date with between

穿精又带淫゛_ 提交于 2021-02-11 12:46:59

问题


How can i select a date stored as varchar (format: "2012.04") with the BETWEEN operator?

I need to select a one year interval on this field.

Now i'm trying with this, but this gives my MySQL syntax error:

SELECT DISTINCT monthcol
FROM bo_alerts
WHERE STR_TO_DATE(monthcol , '%Y.%m') BETWEEN
           (STR_TO_DATE('2012.04', '%Y.%m') AND STR_TO_DATE('2011.03', '%Y.%m'))
ORDER BY monthcol DESC

The dates are now static (for testing), but i need to calculate the second value in the BETWEEN so that it will be exact -1 year to the first value of the BETWEEN section.

Thank you very much!!


回答1:


Given that the dates seem to be fixed length strings, why not use string comparison?:

SELECT DISTINCT monthcol
FROM bo_alerts
WHERE monthcol BETWEEN '2011.03' AND '2012.04'
ORDER BY monthcol DESC

Notice that I reversed the order of the dates to satisfy most SQL implementations having the first less than the second.




回答2:


Renove '.' from date it will work.

Try below query :

SELECT DISTINCT monthcol 
FROM bo_alerts 
WHERE concat(LEFT(monthcol,4),RIGHT(monthcol,2)) BETWEEN 201204  AND 201103
ORDER BY monthcol DESC


来源:https://stackoverflow.com/questions/10206117/query-varchar-date-with-between

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