sql联合顺序

发布于 2024-10-05 11:17:05 字数 336 浏览 1 评论 0原文

我有一张桌子,上面有学生的姓名和身高。我想要一个查询,按字母顺序对身高高于 150 厘米的学生进行排序,对身高低于 150 厘米的学生按姓名降序排列。

像这样的事情:

(select * from students where height >= 150 order by name)  
union 
(select * from students where height < 150 order by name desc)

它不起作用,因为联合弄乱了子查询中行的顺序。我知道这是正常的,联合输出一个集合,并且在一个集合中的顺序并不重要。有类似追加的东西吗?

I have a table students with names and heights. I want a query that order students higher that 150cm alphabetically and students smaller than 150cm in descending order of their names.

Something like this:

(select * from students where height >= 150 order by name)  
union 
(select * from students where height < 150 order by name desc)

it's not working because union mess up the order of the rows in subqueries. I know it's normal, union output a set and in a set the order it's not important. Is there something like append?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暗地喜欢 2024-10-12 11:17:05
   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 |
+------+--------+
   SELECT *
   FROM students
   ORDER BY IF(height >= 150, 1,0 ) DESC, 
            IF(height >= 150, name, '') ASC, 
            name DESC

sample output

+------+--------+
| name | height |
+------+--------+
| a    |    189 |
| m    |    666 |
| thy  |    166 |
| yyy  |   1277 |
| zz   |    101 |
| swq  |    122 |
| n    |    111 |
| g    |    145 |
+------+--------+
放赐 2024-10-12 11:17:05
select *, case when height >= 150 then 1 else 0 end as tallstudent 
from students order by tallstudent, name
select *, case when height >= 150 then 1 else 0 end as tallstudent 
from students order by tallstudent, name
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文