gpt4 book ai didi

sql - Order by 不适用于 Oracle 子查询

转载 作者:行者123 更新时间:2023-12-03 07:30:12 25 4
gpt4 key购买 nike

我正在尝试从表中返回 7 个事件(从今天开始),并按日期顺序排列它们:

SELECT ID
FROM table
where ID in (select ID from table
where DATEFIELD >= trunc(sysdate)
order by DATEFIELD ASC)
and rownum <= 7

如果我删除“order by”,它会很好地返回 ID,并且查询可以工作,但顺序不正确。我将不胜感激任何帮助,因为我似乎无法弄清楚我做错了什么!

(编辑)澄清一下,我之前用过这个,返回的订单确实出问题了:

select ID
from TABLE
where DATEFIELD >= trunc(sysdate)
and rownum <= 7
order by DATEFIELD

谢谢

最佳答案

在处理 ORDER BY 之前应用ROWNUM“函数”的值。这就是为什么它不能按照您使用的方式工作( See the manual 类似的解释)

当使用ROWNUM限制查询并涉及ORDER BY时,排序必须在内部选择中完成,并且限制必须在外部选择中应用:

select *
from (
select *
from table
where datefield >= trunc(sysdate)
order by datefield ASC
)
where rownum <= 7

关于sql - Order by 不适用于 Oracle 子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11882214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com