一尘不染

mysql:搜索存储为varchar的日期之间

sql

我想要 select * from table where dates between (some_date and another_date)

问题是日期存储为varchar

这是我有约会的例子:

7/29/2010 9:53 AM
7/16/2010 7:57:39 AM

请注意,有些记录有几秒钟,有些则没有

我根本不在乎时间,我只需要日期

reporttimedate领域

这是行不通的:

SELECT * FROM batchinfo 
 where cast(reporttime as date) between ('7/28/10' and '7/29/10')

这:

SELECT * from batchinfo WHERE reporttime BETWEEN STR_TO_DATE(7/28/2010, '%m/%/d/%Y %h:%i:%s %p')
                AND STR_TO_DATE(7/29/2010, '%m/%/d/%Y %h:%i:%s %p')

正在返回:

Truncated incorrect datetime value: '7/8/2010 11:47 AM'
Incorrect datetime value: '0.00012009' for function str_to_date

这:

SELECT * from batchinfo WHERE STR_TO_DATE(reporttime, '%m/%/d/%Y %h:%i:%s %p') BETWEEN STR_TO_DATE(7/28/2010, '%m/%/d/%Y')
                                                           AND STR_TO_DATE(7/29/2010, '%m/%/d/%Y')

正在返回:

Incorrect datetime value: '7/8/2010 11:47 AM' for function str_to_date

OMG小马:

我把所有东西都放在第一个空格之前:

SELECT * from batchinfo WHERE STR_TO_DATE(LEFT(reporttime,LOCATE(' ',reporttime)), '%m/%/d/%Y') BETWEEN STR_TO_DATE(7/28/2010, '%m/%/d/%Y')
                                                           AND STR_TO_DATE(7/29/2010, '%m/%/d/%Y')

现在我得到这个返回:

Incorrect datetime value: '7/8/2010' for function str_to_date

阅读 128

收藏
2021-03-10

共1个答案

一尘不染

您想在日期之间进行搜索,并将其存储为日期。通过将它们存储为字符串,您就可以自己射击。您基本上需要从字符串中提取日期部分(使用SUBSTR()LEFT())并将其解析为日期格式(使用STR_TO_DATE())。

这种解决方案的性能将令人赞叹。

STR_TO_DATE(LEFT(reporttime,LOCATE(' ',reporttime)),'%m/%d/%Y') BETWEEN '2010-07-28' AND '2010-07-29'

2021-03-10