Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Sắp xếp timestamp tăng dần trong MySQL

Để sắp xếp cột timestamp theo thứ tự tăng dần, sử dụng ORDER BY ASC kết hợp hàm TIMESTAMP().

Cú pháp

SELECT TIMESTAMP(ten_cot_timestamp) AS ten_alias 
FROM ten_bang 
ORDER BY 1 ASC;

Ví dụ minh họa

Tạo bảng:

mysql> CREATE TABLE Timestamp_TableDemo (
    -> Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> yourTimestamp TIMESTAMP
    -> );

Chèn dữ liệu:

mysql> INSERT INTO Timestamp_TableDemo(yourTimestamp) VALUES('2019-02-06 17:34:57');
mysql> INSERT INTO Timestamp_TableDemo(yourTimestamp) VALUES('2019-02-06 17:32:30');
mysql> INSERT INTO Timestamp_TableDemo(yourTimestamp) VALUES('2019-02-06 17:32:09');

Dữ liệu gốc:

+----+---------------------+
| Id | yourTimestamp       |
+----+---------------------+
|  1 | 2019-02-06 17:34:57 |
|  2 | 2019-02-06 17:32:30 |
|  3 | 2019-02-06 17:32:09 |
+----+---------------------+

Sắp xếp tăng dần:

mysql> SELECT TIMESTAMP(yourTimestamp) AS 'timestampDemo' 
    -> FROM Timestamp_TableDemo 
    -> ORDER BY 1 ASC;

Kết quả:

+---------------------+
| timestampDemo       |
+---------------------+
| 2019-02-06 17:32:09 |
| 2019-02-06 17:32:30 |
| 2019-02-06 17:34:57 |
+---------------------+

Lưu ý: ORDER BY 1 nghĩa là sắp xếp theo cột đầu tiên trong SELECT. Có thể dùng ORDER BY yourTimestamp ASC trực tiếp cho đơn giản hơn.