Dùng STR_TO_DATE() trong ORDER BY để chuyển chuỗi thời gian AM/PM thành giá trị TIME để sắp xếp đúng thứ tự thời gian thực.
Ví dụ
Tạo bảng lưu giờ logout dạng chuỗi '09:45 PM':
mysql> create table DemoTable (
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
UserLogoutTime varchar(200)
);
Query OK, 0 rows affected (0.97 sec)Dữ liệu: '09:45 PM', '11:56 AM', '01:01 AM', '02:01 PM', '04:10 PM'
Sắp xếp theo thời gian thực
mysql> select UserLogoutTime from DemoTable ORDER BY STR_TO_DATE(UserLogoutTime, '%l:%i %p');
+----------------+ | UserLogoutTime | +----------------+ | 01:01 AM | | 11:56 AM | | 02:01 PM | | 04:10 PM | | 09:45 PM | +----------------+
Format string:
%l- giờ 12h (1-12)%i- phút (00-59)%p- AM/PM
Lưu ý: Sắp xếp chuỗi trực tiếp ('09:45 PM' vs '11:56 AM') sẽ sai vì so sánh lexicographic (theo ký tự). Cần parse thành TIME để so sánh đúng.