searching data between dates stored in varchar in

2019-01-26 13:27发布

问题:

I am storing my dates in column server_date_time in varchar in dd/mm/yyyy format and i want to fetch the records lying between some dates so i have used the query

    select * from activity_emp 
where date_format(str_to_date(substr(server_date_time,1,10),'%d/%m/%Y'),'%d/%m/%Y')>=
'29/09/2012'
    and date_format(str_to_date(substr(server_date_time,1,10),'%d/%m/%Y'),'%d/%m/%Y')<=
'07/10/2012';

I have converted varchar to string in query but my query return query data only related to 29/09/2012 and 30/09/2012. It should also return query for the month of October

回答1:

Try with this. You can input date in dd/mm/yyyy format as in your question...

SELECT * FROM activity_emp
WHERE STR_TO_DATE(server_date_time, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/08/2012', '%d/%m/%Y')
    AND STR_TO_DATE('07/10/2012', '%d/%m/%Y')

Update: I strongly recommend you to change datatype from VARCHAR to DATETIME

Cheers!!!



回答2:

Try this one -

SELECT * FROM activity_emp
WHERE STR_TO_DATE(server_date_time, '%d/%m/%Y')
  BETWEEN '2012-09-29' AND '2012-09-30'

But it is better to store server_date_time in DATETIME data type so that MySQL can use index.



回答3:

STR_TO_DATE is enough. DATE_FORMAT changes it back to VARCHAR

SELECT...
FROM...
WHERE str_to_date(substr(server_date_time,1,10),'%d/%m/%Y') 
         BETWEEN '29/09/2012' AND '07/10/2012'

when dealing date please use DATE or DATETIME data type. This will avoid you from doing casting which affects the performance of the query.



回答4:

If you are storing the dates always in dd/mm/yyyy in the column then this is an easy task:

SELECT * from activity_emp 
where server_date_time BETWEEN '29/09/2012' AND '07/10/2012'

Isn't this enough? Hope it helps you



回答5:

SELECT * 
FROM  `activity_emp` 
WHERE STR_TO_DATE(  `column_name` ,  '%d/%m/%Y' ) 
BETWEEN  '2010-10-10'
AND  '2010-11-10'


回答6:

This is Simple and Easy to understand Date Query to search between Two Dates

Date that stored in datebase in like 01/01/2016 and datatype is varchar
SELECT * FROM `test` WHERE STR_TO_DATE(`test`.`date`, '%d/%m/%Y') BETWEEN '2016-01-01' AND '2016-01-31' ORDER BY `test`.`date` ASC