今天发现了一条奇怪了sql语句,遂研究了一下, 以下是研究结果, 个人理解, 仅供参考
后面的排序条件是这样的:
order by num = 2 desc
测试表
CREATE TABLE `student` (
`stuid` varchar(16) NOT NULL COMMENT '学号',
`stunm` varchar(20) NOT NULL COMMENT '学生姓名',
`num` int(11) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`stuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO test.student (stuid,stunm,num,age,score) VALUES
('1001','张三',1,28,0),
('1002','李四',2,26,0),
('1003','赵二',2,29,0),
('1004','王五',1,31,50),
('1005','刘青',3,27,0),
('1006','周明',3,31,40);
select * from student order by num = 2 asc
stuid|stunm|num|age|score|
-----+-----+---+---+-----+
1001 |张三 | 1| 28| 0|
1004 |王五 | 1| 31| 50|
1005 |刘青 | 3| 27| 0|
1006 |周明 | 3| 31| 40|
1002 |李四 | 2| 26| 0|
1003 |赵二 | 2| 29| 0|
select * from student order by num = 2 desc
stuid|stunm|num|age|score|
-----+-----+---+---+-----+
1002 |李四 | 2| 26| 0|
1003 |赵二 | 2| 29| 0|
1001 |张三 | 1| 28| 0|
1004 |王五 | 1| 31| 50|
1005 |刘青 | 3| 27| 0|
1006 |周明 | 3| 31| 40|
select * from student order by num = 2 desc, age desc
stuid|stunm|num|age|score|
-----+-----+---+---+-----+
1003 |赵二 | 2| 29| 0|
1002 |李四 | 2| 26| 0|
1004 |王五 | 1| 31| 50|
1006 |周明 | 3| 31| 40|
1001 |张三 | 1| 28| 0|
1005 |刘青 | 3| 27| 0|
select * from student order by num = 2 desc, age asc
stuid|stunm|num|age|score|
-----+-----+---+---+-----+
1002 |李四 | 2| 26| 0|
1003 |赵二 | 2| 29| 0|
1005 |刘青 | 3| 27| 0|
1001 |张三 | 1| 28| 0|
1004 |王五 | 1| 31| 50|
1006 |周明 | 3| 31| 40|
结论:
等于是把所有数据分为两组, num=2 的记录作为一组, num<>2或num is null 作为另一组,然后对这两组排序
还可以这样写:
select * from student order by num = 2 or num = 3 desc
select * from student order by num = 2 or num = 3 asc, num desc
stuid|stunm|num|age|score|
-----+-----+---+---+-----+
1001 |张三 | 1| 28| 0|
1004 |王五 | 1| 31| 50|
1005 |刘青 | 3| 27| 0|
1006 |周明 | 3| 31| 40|
1002 |李四 | 2| 26| 0|
1003 |赵二 | 2| 29| 0|
=======分割线=========
select * from student order by num = 2 or num = 3 desc, num asc
stuid|stunm|num|age|score|
-----+-----+---+---+-----+
1002 |李四 | 2| 26| 0|
1003 |赵二 | 2| 29| 0|
1005 |刘青 | 3| 27| 0|
1006 |周明 | 3| 31| 40|
1001 |张三 | 1| 28| 0|
1004 |王五 | 1| 31| 50|
order by 2 这样的见过,数字就代表根据那一列排序,从 1 开始
select * from student order by 4
stuid|stunm|num|age|score|
-----+-----+---+---+-----+
1002 |李四 | 2| 26| 0|
1005 |刘青 | 3| 27| 0|
1001 |张三 | 1| 28| 0|
1003 |赵二 | 2| 29| 0|
1004 |王五 | 1| 31| 50|
1006 |周明 | 3| 31| 40|
等价于:
select * from student order by age
疑问: 我能分三组,然后对这三组进行排序吗?