简体   繁体   中英

MySQL Order by string field as date

I face the following issue: I have a database which holds data in the form of username, somedata, date.

Unfortunately, 'date' field is a string field which holds date which came from javascript code in the form eg "Sun Nov 09 2014 18:34:39 GMT+0530 (IST)"

I need to export a file with data in chronological order and because data is huge I cannot sort it manually of course, I need it to be done through mysql.

For now, I use the following code which does not achieve what I need to

 SELECT *
 FROM log
 ORDER BY STR_TO_DATE(date, '%d/%m/%Y'),username 
 INTO OUTFILE '/tmp/file8'
 FIELDS ENCLOSED BY '"' TERMINATED BY ';' ESCAPED BY '"'
 LINES TERMINATED BY '\r\n';

Any ideas? Thanks.

Since the dates are stored in the format Sun Nov 09 2014 18:34:39 GMT+0530 (IST)

str_to_date that you are using will return null

mysql> select STR_TO_DATE('Sun Nov 09 2014 18:34:39 GMT+0530 (IST)', '%d/%m/%Y') as date;
+------+
| date |
+------+
| NULL |
+------+

The correct format is

mysql> select str_to_date('Sun Nov 09 2014 18:34:39 GMT+0530 (IST)','%a %b %d %Y %H:%i:%s') as date ;
+---------------------+
| date                |
+---------------------+
| 2014-11-09 18:34:39 |
+---------------------+

You need to supply the proper date formatting arguments as listed here http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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