首頁 >資料庫 >mysql教程 >MySQL中按日期和時間降序排序?

MySQL中按日期和時間降序排序?

王林
王林轉載
2023-09-05 08:21:041074瀏覽

MySQL中按日期和時間降序排序?

讓我們建立一個表格來按升序對日期和時間進行排序。建立表格的查詢如下 -

mysql> create table SortByDateAndTime
   -> (
   -> UserId int,
   -> UserName varchar(100),
   -> IssueDate date,
   -> IssueTime time
   -> );
Query OK, 0 rows affected (0.60 sec)

使用insert指令在表格中插入記錄。查詢如下-

mysql> insert into SortByDateAndTime values(1,'John','2018-12-16','10:30');
Query OK, 1 row affected (0.14 sec)

mysql> insert into SortByDateAndTime values(2,'Bob','2018-12-16','10:10');
Query OK, 1 row affected (0.14 sec)

mysql> insert into SortByDateAndTime values(3,'Carol','2018-12-16','10:20');
Query OK, 1 row affected (0.10 sec)

mysql> insert into SortByDateAndTime values(4,'Sam','2018-12-16','10:00');
Query OK, 1 row affected (0.15 sec)

使用select 語句顯示表中所有記錄的查詢如下-

mysql> select *from SortByDateAndTime;

輸出

+--------+----------+------------+-----------+
| UserId | UserName | IssueDate  | IssueTime |
+--------+----------+------------+-----------+
|     1 | John      | 2018-12-16 | 10:30:00  |
|     2 | Bob       | 2018-12-16 | 10:10:00  |
|     3 | Carol     | 2018-12-16 | 10:20:00  |
|     4 | Sam       | 2018-12-16 | 10:00:00  |
+--------+----------+------------+-----------+
4 rows in set (0.00 sec)

這是按降序對日期和時間進行排序的查詢-

mysql> select UserId,UserName,date(IssueDate) as date1,IssueTime from
SortByDateAndTime
   -> order by date(IssueDate)desc,IssueTime desc;

以下是以排序的日期和時間顯示的輸出-

+--------+----------+------------+-----------+
| UserId | UserName | date1      | IssueTime |
+--------+----------+------------+-----------+
|      1 | John     | 2018-12-16 | 10:30:00  |
|      3 | Carol    | 2018-12-16 | 10:20:00  |
|      2 | Bob      | 2018-12-16 | 10:10:00  |
|      4 | Sam      | 2018-12-16 | 10:00:00  |
+--------+----------+------------+-----------+
4 rows in set (0.00 sec)

或您可以使用另一個查詢來對日期和時間進行排序。查詢如下 -

mysql> select UserId,UserName,date(IssueDate) as date1,IssueTime from
SortByDateAndTime
   -> order by date(IssueDate) desc,IssueTime asc;

輸出

+--------+----------+------------+-----------+
| UserId | UserName | date1      | IssueTime |
+--------+----------+------------+-----------+
|      4 | Sam      | 2018-12-16 | 10:00:00  |
|      2 | Bob      | 2018-12-16 | 10:10:00  |
|      3 | Carol    | 2018-12-16 | 10:20:00  |
|      1 | John     | 2018-12-16 | 10:30:00  |
+--------+----------+------------+-----------+
4 rows in set (0.00 sec)
#

以上是MySQL中按日期和時間降序排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除