MySQL 日期格式 DD/MM/YYYY 选择查询?

mysqlmysqli database

使用 select 和 order by 按降序格式化日期 DD/MM/YYYY。语法如下 −

SELECT *FROM yourTableName
where yourDatetimeColumnName order by
STR_TO_DATE(yourDatetimeColumnName,’%d/%m%Y’) desc;

上述语法将按降序排列日期。要理解上述语法,让我们首先创建一个表。创建表的查询如下 −

mysql> create table DateFormatWithSelect
   -> (
   -> UserId int,
   -> UserName varchar(100),
   -> UserLoginDatetime varchar(100)
   -> );
Query OK, 0 rows affected (0.58 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下 −

mysql> insert into DateFormatWithSelect values(101,'John','20/10/2016');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DateFormatWithSelect values(102,'David','21/09/2015');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DateFormatWithSelect values(103,'Carol','21/12/2018');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DateFormatWithSelect values(104,'Mike','2/8/2014');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DateFormatWithSelect values(105,'Sam','21/11/2017');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DateFormatWithSelect values(106,'Bob','21/12/2013');
Query OK, 1 row affected (0.18 sec)

使用 select 命令显示表中的所有记录。查询如下 −

mysql> select *from DateFormatWithSelect;

The following is the outpu −

+--------+----------+-------------------+
| UserId | UserName | UserLoginDatetime |
+--------+----------+-------------------+
|    101 | John     | 20/10/2016        |
|    102 | David    | 21/09/2015        |
|    103 | Carol    | 21/12/2018        |
|    104 | Mike     | 2/8/2014          |
|    105 | Sam      | 21/11/2017        |
|    106 | Bob      | 21/12/2013        |
+--------+----------+-------------------+
6 rows in set (0.00 sec)

以下是将日期格式化为 DD/MM/YYYY 格式的 SELECT −

mysql> select *from DateFormatWithSelect
   -> where UserLoginDatetime order by str_to_date(UserLoginDatetime,'%d/%m/%Y') desc;

输出

+--------+----------+-------------------+
| UserId | UserName | UserLoginDatetime |
+--------+----------+-------------------+
|    103 | Carol    | 21/12/2018        |
|    105 | Sam      | 21/11/2017        |
|    101 | John     | 20/10/2016        |
|    102 | David    | 21/09/2015        |
|    104 | Mike     | 2/8/2014          |
|    106 | Bob      | 21/12/2013        |
+--------+----------+-------------------+
6 rows in set, 6 warnings (0.00 sec)

相关文章