我有一个名字和高度的学生表。我想要一个查询,按字母顺序排列150cm以上的学生,按照名字的降序排列小于150cm的学生。
这样的事情:
(select * from students where height >= 150 order by name)
union
(select * from students where height < 150 order by name desc)
它不起作用,因为联合搞乱了子查询中行的顺序。我知道这是正常的,联合输出一组,并且在一组中它的顺序并不重要。有什么像追加?
答案 0 :(得分:8)
SELECT *
FROM students
ORDER BY IF(height >= 150, 1,0 ) DESC,
IF(height >= 150, name, '') ASC,
name DESC
示例输出
+------+--------+
| name | height |
+------+--------+
| a | 189 |
| m | 666 |
| thy | 166 |
| yyy | 1277 |
| zz | 101 |
| swq | 122 |
| n | 111 |
| g | 145 |
+------+--------+
答案 1 :(得分:1)
select *, case when height >= 150 then 1 else 0 end as tallstudent
from students order by tallstudent, name