MySQL ORDER BY 日期字段不在日期格式中?
以下是按非日期格式的日期字段排序的语法
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) -> ); Query OK, 0 rows affected (0.73 sec)
使用 insert 命令在表中插入一些记录。查询如下 −
mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('01/10/2012'); Query OK, 1 row affected (0.20 sec) mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('03/11/2010'); Query OK, 1 row affected (0.15 sec) mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('04/09/2018'); Query OK, 1 row affected (0.14 sec) mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('31/01/2019'); Query OK, 1 row affected (0.17 sec) mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('21/04/2017'); Query OK, 1 row affected (0.21 sec) mysql> insert into orderByDateFormatDemo(ArrivalDatetime) values('23/05/2016'); Query OK, 1 row affected (0.12 sec)
使用 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)
以下是按非日期格式的日期字段进行排序的查询
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)
广告