MySQL ORDER BY Date field which is not in date for

2020-02-10 07:13发布

I have a field containing dates in this format DD/MM/YYYY and I need to order the results DESC by this field, but it is saved as a VARCHAR and I cannot change this. Is there a workaround?

There really is no way for me to change the field type so please don't say this is a bad way to do this as I already know. I just need to know if it is possible.

Thanks for any help and advice in advance.

标签: php mysql
5条回答
成全新的幸福
2楼-- · 2020-02-10 07:19

You can do it by the following way,

SELECT ...
FROM ...
ORDER BY STR_TO_DATE(yourDate,'%d-%m-%Y') DESC
查看更多
够拽才男人
3楼-- · 2020-02-10 07:23
ORDER BY CONCAT(SUBSTR(field, 7, 4), SUBSTR(field, 4, 2), SUBSTR(field, 1, 2)) DESC
查看更多
4楼-- · 2020-02-10 07:26

use this

STR_TO_DATE

   SELECT * FROM table_name ORDER BY  STR_TO_DATE(date_field, '%d-%M-%Y') DESC
查看更多
Melony?
5楼-- · 2020-02-10 07:37

Use STR_TO_DATE() MySQL function:

SELECT * FROM your_table ORDER BY STR_TO_DATE(your_date_column, '%d/%M/%Y') DESC;

sidenote: STR_TO_DATE converts String to Date while DATE_FORMAT converts Date to String

查看更多
地球回转人心会变
6楼-- · 2020-02-10 07:39

Using STR_TO_DATE:

http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_str-to-date

...
order by str_to_date(myCol, '%d/%m/%Y')
查看更多
登录 后发表回答