1、创建测试表,
create table test_order(id number, value1 number, value2 number)
2、插入测试数据
insert into test_order values(1,1001,2001)
insert into test_order values(2,1002,2002)
insert into test_order values(3,1003,2003)
insert into test_order values(4,1004,2004)
insert into test_order values(5,1005,2005)
3、查询表中所有记录数,select t.*, rowid from test_order t,
4、编写sql,按value1字段做升序,按value2字段做降序,
select t.*,
row_number() over(order by value1) rn1,
row_number() over(order by value2 desc) rn12
from test_order t
MySQL排序 有时候很容易记混,我这里把他记录了下:
desc是降序
asc是升序(默认不写就是升序)
MySql语句:
1.带条件的排序
2.不带条件的sql直接排序
1、单列排序SELECT * FROM test1 ORDER BY date_time
默认升序,降序后面接"DESC"即可。
2、多列排序
SELECT * FROM test1 ORDER BY `status`, date_time DESC
首先按`status`字段排序,若`status`相等,则按data_time排序。
3、自定义排序
SELECT * FROM test1 ORDER BY FIELD(`status`, 3, 2, 4, 1, 5), date_time DESC
使用"FIELD()"函数,可指定顺序。
4、其他条件排序
先按大于等于当前时间升序,再按小于当前时间降序,支持分页。
SELECT * FROM test1 ORDER BY date_time <NOW(), IF(date_time <NOW(), 0, date_time), date_time DESC
附加SQL脚本:
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
INSERT INTO `test1` VALUES
(NULL, '测试1', '2018-03-05 11:09:00', 1),(NULL, '测试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, '李某某', '2018-04-17 11:09:00', 1),(NULL, '饭某某', '2018-04-20 13:09:00', 2),
(NULL, '赵', '2018-04-20 01:09:00', 4),(NULL, '倩', '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, '盖茨', '2018-04-21 11:09:00', 1),
(NULL, '部长', '2018-04-24 11:09:00', 4),(NULL, '李总', '2018-04-20 11:09:00', 5),(NULL, '张总', '2018-04-29 11:09:00', 2),
(NULL, '王总', '2018-04-19 11:09:00', 3),(NULL, '唐总', '2018-05-01 11:09:00', 2)
参考的这篇文档Mysql排序方式
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)