How to convert/cast varchar to date?

余生长醉 提交于 2020-01-12 10:17:07

问题


I have a date column with data type varchar(mm-dd-yyyy) in mySQL 5.1. How do I convert it to DATE?

Here is what I have so far -

SELECT id, date 
FROM tableName 
WHERE (CAST((SUBSTRING (date FROM 7 FOR 4 )||'/'||SUBSTRING (date FROM 4 FOR 2 )||'/'||SUBSTRING (date FROM 1 FOR 2 )) AS DATE) >= '01/01/2012' ) 
ORDER BY date DESC;

Getting this

error - #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM 7 FOR 4 )

Please help.


回答1:


You can use MySQL's STR_TO_DATE() function

SELECT id, date 
FROM tableName 
WHERE STR_TO_DATE(date,'%Y-%m-%d') >= '01/01/2012' 
ORDER BY date DESC;

Although I suspect you will have an easier time using Unix Timestamps

SELECT id, date 
FROM tableName 
WHERE UNIX_TIMESTAMP(STR_TO_DATE(date,'%d/%m/%Y')) >= UNIX_TIMESTAMP('01/01/2012') 
ORDER BY date DESC;


来源:https://stackoverflow.com/questions/11583045/how-to-convert-cast-varchar-to-date

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