MySQL ORDER BY Date字段不是日期格式?
以下是非日期格式的按日期排序的语法
select *from yourTableName order by STR_TO_DATE(yourColumnName,'%d/%m/%Y') DESC;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table orderByDateFormatDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ArrivalDatetime varchar(100) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('01/10/2012'); mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('03/11/2010'); mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('04/09/2018'); mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('31/01/2019'); mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('21/04/2017'); mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('23/05/2016');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from orderByDateFormatDemo;
以下是输出
+----+-----------------+ | Id | ArrivalDatetime | +----+-----------------+ | 1 | 01/10/2012 | | 2 | 03/11/2010 | | 3 | 04/09/2018 | | 4 | 31/01/2019 | | 5 | 21/04/2017 | | 6 | 23/05/2016 | +----+-----------------+ 6 rows in set (0.00 sec)
这是对非日期格式的ORDERBY日期字段的查询
mysql> select *from orderByDateFormatDemo -> order by -> STR_TO_DATE(ArrivalDatetime,'%d/%m/%Y') DESC;
以下是输出
+----+-----------------+ | Id | ArrivalDatetime | +----+-----------------+ | 4 | 31/01/2019 | | 3 | 04/09/2018 | | 5 | 21/04/2017 | | 6 | 23/05/2016 | | 1 | 01/10/2012 | | 2 | 03/11/2010 | +----+-----------------+ 6 rows in set (0.04 sec)