mysql: searching BETWEEN dates stored as varchar

后端 未结 6 1278
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 14:20

i would like to select * from table where dates between (some_date and another_date)

the problem is that the dates are stored as varchar!

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 15:11

    Use STR_TO_DATE to convert the strings to the DateTime data type. The format shorthand is found under DATE_FORMAT:

    STR_TO_DATE(column, '%m/%/d/%Y %h:%i:%s %p')
    

    The problem is, you'll have to update the VARCHAR dates to all be the same format first, before you can use:

    WHERE STR_TO_DATE(reporttime, '%m/%/d/%Y %h:%i:%s %p') BETWEEN STR_TO_DATE(some_date, '%m/%/d/%Y')
                                                               AND STR_TO_DATE(another_date, '%m/%/d/%Y')
    

    Date formats are not consistent (some use hyphens, others slashes and Year/Month/day order can be totally different...), so STR_TO_DATE is the most accommodating & consistent means of turning a string into a DateTime. Only after the value is DateTime, does Date/Time functionality become available like DATE() to get only the date portion...

    Because of the data type change, an index on some_date & another_date columns can not be used.

提交回复
热议问题