简体   繁体   English

选择日期时间大于指定日期的记录

[英]Select records where datetime is greater than the specified date

Problem 问题

I am trying to fetch all the records from table where date_time field is greater than ' Thu, 11 Jul 2013 ' by running the below mentioned query. 我试图通过运行下面提到的查询从date_time字段大于' 星期四,2013年7月11日 '的表中获取所有记录。 Value in the date_time field is stored in this format => Thu, 11 Jul 2013 08:29:37 . date_time字段中的值以此格式存储=> Thu,2013年7月11日08:29:37 Any help will be great. 任何帮助都会很棒。

Datatype of field date_time is varchar 字段date_time的数据类型是varchar

Query 询问

SELECT * FROM table_name 
WHERE username = 'mark@example.com' 
AND STR_TO_DATE(date_time, '%a, %e %b %Y %H:%i:%s') >= 'Thu, 11 Jul 2013 00:00:00';

Here is yet another great example of why you should implement date/time fields in MySQL using the date, datetime, or timestamp field types and let your application deal with how to format the date for output. 这是另一个很好的例子,说明为什么你应该使用date,datetime或timestamp字段类型在MySQL中实现日期/时间字段,并让你的应用程序处理如何格式化输出日期。

Right now you are going to need to do something like: 现在你需要做类似的事情:

SELECT * FROM table_name 
WHERE username = 'mark@example.com' 
AND STR_TO_DATE(date_time, '%a, %e %b %Y %H:%i:%s') >= STR_TO_DATE('Thu, 11 Jul 2013 00:00:00', '%a, %e %b %Y %H:%i:%s');

This query will not be able to use any index you have on your date_time field, so the query will be very inefficient. 此查询将无法使用您在date_time字段上的任何索引,因此查询效率非常低。 It will need to perform a full table scan, converting the value of each row in order to make the comparison. 它需要执行全表扫描,转换每行的值以进行比较。

What you should be doing is: 你应该做的是:

SELECT * FROM table_name 
WHERE username = 'mark@example.com' 
AND date_time >= STR_TO_DATE('Thu, 11 Jul 2013 00:00:00', '%a, %e %b %Y %H:%i:%s');

Here if you have your field in the MySQL datetime format, you just need to convert the input to a this format for matching. 这里,如果您的字段采用MySQL日期时间格式,则只需将输入转换为此格式即可进行匹配。 Since your field data is already in this format, you will be able to utilize an index for the search. 由于您的现场数据已采用此格式,因此您可以使用索引进行搜索。

You are trying to compare a date with a String. 您正在尝试将日期与字符串进行比较。

The str_to_date function application is correct, but you are not comparing to a date. str_to_date函数应用程序是正确的,但您没有与日期进行比较。

The right way to do it is: 正确的方法是:

select * from yourTable
where STR_TO_DATE(date_time, '%a, %e %b %Y %H:%i:%s') >= '2013-07-11 00:00:00'

Notice that the date format is YYYY-MM-DD HH:mm:ss (which is MySQL default date format). 请注意,日期格式为YYYY-MM-DD HH:mm:ss (这是MySQL的默认日期格式)。

Of course, you can also compare to str_to_date results: 当然,您也可以与str_to_date结果进行比较:

... where STR_TO_DATE(date_time, '%a, %e %b %Y %H:%i:%s') >= STR_TO_DATE('Thu, 11 Jul 2013 00:00:00', '%a, %e %b %Y %H:%i:%s')

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

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