问题
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