Data sorting is very common. Today, I will introduce several sorting methods of MySql, which I have used recently. I hope it can be helpful to everyone.
Here first create a normal table,
CREATE TABLE `test1` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `date_time` datetime NOT NULL, `status` int(5) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
Add some more test data,
INSERT INTO `test1` VALUES (NULL, 'Test 1', '2018-03-05 11:09:00', 1),(NULL, 'Test 2', '2018-03-06 11:09:00', 1),(NULL , 'abc', '2018-03-07 11:09:00', 1), (NULL, 'def', '2018-04-08 11:09:00', 2),(NULL, 'Li Moumou', '2018-04-17 11:09:00', 1),(NULL , 'fan XX', '2018-04-20 13:09:00', 2), (NULL, 'Zhao', '2018-04-20 01:09:00', 4),(NULL, 'Qian', '2018-04-28 11:09:00', 2),(NULL, ' andy', '2018-04-30 11:09:00', 1), (NULL, 'tony', '2018-05-08 11:09:00', 4),(NULL, 'tom', '2018-05-07 11:09:00', 3),(NULL, 'bill', '2018-05-18 11:09:00', 3), (NULL, 'james', '2018-06-07 11:09:00', 4),(NULL, 'anthony', '2018-06-18 11:09:00', 2),(NULL, ' Gates', '2018-04-21 11:09:00', 1), (NULL, 'Minister', '2018-04-24 11:09:00', 4),(NULL, 'Mr. Li', '2018-04-20 11:09:00', 5),(NULL, 'Mr. Zhang', '2018-04-29 11:09:00', 2), (NULL, 'Mr. Wang', '2018-04-19 11:09:00', 3),(NULL, 'Mr. Tang', '2018-05-01 11:09:00', 2);
With the data, start to do some sorting for the data;
1. Sort by single column
SELECT * FROM test1 ORDER BY date_time
The default ascending order, the descending order is followed by "DESC".
2, multi-column sorting
SELECT * FROM test1 ORDER BY `status`, date_time DESC
First sort by `status` field, if `status` are equal, then sort by data_time.
3, custom sorting
SELECT * FROM test1 ORDER BY FIELD(`status`, 3, 2, 4, 1, 5), date_time DESC
Using the "FIELD()" function, the order can be specified.
4. Sort by other conditions
First, ascending order is greater than or equal to the current time, and then descending by less than the current time, paging is supported.
SELECT * FROM test1 ORDER BY date_time < NOW(), IF(date_time < NOW(), 0, date_time), date_time DESC