sql - Oracle sql查询Order By给出不同的结果

标签 sql database oracle sql-order-by

输出

查询 1:

select id from users
order by case when DEVIATION_LEVEL=2863 then 1 else 2 end

800019  
800030  
800040  
800003  
800007  
800015  
800025  
800026....etc   

输出 查询 2:

select id from
    (select id from users
     order by case when DEVIATION_LEVEL=2863 then 1 else 2 end)
where rownum<=16;

800019
800030
800028
800020
800021
800018
800012
800161...etc

为什么第二个查询的顺序发生变化?请提出正确的解决方案以限制第一个查询结果的大小。

最佳答案

当您执行不带 ORDER BY 子句的 SELECT 查询时,结果的顺序是不确定的。如果您想要或需要具有一致的排序行为,请在顶层 SELECT 中使用 ORDER BY 子句。

然而,当您使用 ROWNUM 字段限制行时,在 oracle 中存在异常。在这种情况下,ROWNUM 过滤器会在应用 order by 子句之前减少结果集,从而删除本应排在第一位的行。

select id from users
order by case when DEVIATION_LEVEL=2863 then 1 else 2, id;

select id from
    (select id from users
     order by case when DEVIATION_LEVEL=2863 then 1 else 2 end, id)
where rownum<=16;

关于sql - Oracle sql查询Order By给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186895/

相关文章:

sql - 'Interval' 的 JPA Hibernate 查询问题

mysql - 更新数量以减去 1

mysql - sqlyog 上的 "please select equal number of source and reference"

oracle - 更新Elasticsearch中关于向我的数据库添加新文档的索引

sql - 从 Oracle DB 删除数据

php - IN 查询计数随着页面加载速度非常慢,寻找另一个解决方案

mysql - 查询没有像预期的那样工作

php - 如何在单个查询中执行多个选择查询并仍然检索值

sql - 从一个巨大的表中检索计数的更节省空间的方法

java - 使用 Oracle SQL 结果集填充 Java swing JComboBox