简体   繁体   English

varchar日期时间比较问题

[英]varchar date time comparison issue

I have a legacy table which has a varchar column represent date, format is MM/DD/YYYY (eg 01/08/2015). 我有一个旧表,该表的varchar列表示日期,格式为MM/DD/YYYY (例如2015年8月8日)。 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). 因为它是varchar,所以执行数据范围选择并不方便(当我使用<或>种类比较时,将转到varchar / string比较,这与日期比较的结果有所不同)。

For example, I want to select only rows which dates are between 01/08/2015 and 01/10/2015. 例如,我只选择日期在2015年8月8日到2015年10月10日之间的行。 Any smart solution is appreciated, and I cannot change the data type of varchar to date in my existing table. 感谢任何智能解决方案,并且我无法在现有表中更改varchar的数据类型。

I am using MySQL Workbench/MySQL. 我正在使用MySQL Workbench / MySQL。

Varchar dates are evil and they are not real date, the best solution is to use mysql's native date data types. Varchar日期是邪恶的,它们不是真实日期,最佳解决方案是使用mysql的本地日期数据类型。

Since you can't change the datatype you may use str_to_date() function and here how it works 由于您无法更改数据类型,因此可以使用str_to_date()函数及其运行方式

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

So the query for select would be 所以选择查询将是

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')

您可以使用STR_TO_DATE将日期转换为字符串:

STR_TO_DATE(yourdatefield, '%m/%d/%Y')
SELECT STR_TO_DATE(got_fired_at, '%m/%d/%Y') BETWEEN ? AND ? FROM firings;

(字段/表名保证随机选择)

There are many answers which addresses many different way of converting the string to date. 有许多答案解决了将字符串转换为日期的许多不同方式。

You may choose whichever is perfect for your need 您可以选择最适合您的需求

SELECT * FROM `your_table` WHERE DATE_FORMAT(my_column_with_the_string_date, "%Y-%m-%d") <= '2011-09-30'

DATE_FORMAT can be used to convert your date string to any format: I will use the NOW() function instead of string to list different formats that are supported DATE_FORMAT可用于将日期字符串转换为任何格式:我将使用NOW()函数代替字符串来列出受支持的不同格式

DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')
DATE_FORMAT(NOW(),'%m-%d-%Y')
DATE_FORMAT(NOW(),'%d %b %y')
DATE_FORMAT(NOW(),'%d %b %Y %T:%f')

The output of the above is: 上面的输出是:

Nov 04 2014 11:45 PM
11-04-2014
04 Nov 14
04 Nov 2014 11:45:34:243

You can modify your query accordingly 您可以相应地修改查询

使用MySQL的STR_TO_DATE函数将日期字符串解析为日期对象,然后进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM