varchar日期时间比较问题 [英] varchar date time comparison issue

查看:104
本文介绍了varchar日期时间比较问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧表,该表的varchar列表示日期,格式为MM/DD/YYYY(例如2015年1月8日).由于数据范围选择是varchar,所以执行数据范围选择并不方便(当我使用<或>种类比较时,将转到varchar/string比较,这与日期比较的结果有所不同).

I have a legacy table which has a varchar column represent date, format is MM/DD/YYYY (e.g. 01/08/2015). It is not convenient to perform data range selection since it is a varchar (when I use < or > kinds comparison, it goes to varchar/string comparison, which have different results from date comparision).

例如,我只选择日期在2015年8月8日到2015年10月10日之间的行.任何智能解决方案都值得赞赏,我无法在现有表中更改varchar的数据类型为最新的数据.

For example, I want to select only rows which dates are between 01/08/2015 and 01/10/2015. Any smart solution is appreciated, and I cannot change the data type of varchar to date in my existing table.

我正在使用MySQL Workbench/MySQL.

I am using MySQL Workbench/MySQL.

推荐答案

Varchar日期是邪恶的,它们不是真实日期,最好的解决方案是使用mysql的本地日期数据类型.

Varchar dates are evil and they are not real date, the best solution is to use mysql's native date data types.

由于无法更改数据类型,因此可以使用str_to_date()函数及其作用方式

Since you can't change the datatype you may use str_to_date() function and here how it works

mysql> select str_to_date('01/08/2015','%d/%m/%Y') as d ;
+------------+
| d          |
+------------+
| 2015-08-01 |
+------------+

所以选择查询将是

select * from table_name
where
str_to_date(date_column,'%d/%m/%Y')
between
str_to_date('01/08/2015','%d/%m/%Y')
and
str_to_date('01/10/2015','%d/%m/%Y')

这篇关于varchar日期时间比较问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆