MySQL 日期格式 DD/MM/YYYY 選擇查詢?


使用 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;

輸出如下:

+--------+----------+-------------------+
| 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)

更新時間:2019 年 7 月 30 日

4K+ 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.