Oracle SELECT TOP 10 records(Oracle SELECT TOP 10 记录)
问题描述
我对 Oracle 中的 SQL 语句有一个大问题.我想选择 STORAGE_DB 排序的前 10 条记录,这些记录不在其他选择语句的列表中.
I have an big problem with an SQL Statement in Oracle. I want to select the TOP 10 Records ordered by STORAGE_DB which aren't in a list from an other select statement.
这个适用于所有记录:
SELECT DISTINCT
APP_ID,
NAME,
STORAGE_GB,
HISTORY_CREATED,
TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE
FROM HISTORY WHERE
STORAGE_GB IS NOT NULL AND
APP_ID NOT IN (SELECT APP_ID
FROM HISTORY
WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') = '06.02.2009')
但是当我添加
AND ROWNUM <= 10
ORDER BY STORAGE_GB DESC
我得到了某种随机"记录.我认为是因为限制发生在订单之前.
I'm getting some kind of "random" Records. I think because the limit takes in place before the order.
有人有好的解决方案吗?另一个问题:这个查询真的很慢(10k+ 条记录)
Does someone has an good solution? The other problem: This query is realy slow (10k+ records)
推荐答案
您需要将当前查询放入子查询中,如下所示:
You'll need to put your current query in subquery as below :
SELECT * FROM (
SELECT DISTINCT
APP_ID,
NAME,
STORAGE_GB,
HISTORY_CREATED,
TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') AS HISTORY_DATE
FROM HISTORY WHERE
STORAGE_GB IS NOT NULL AND
APP_ID NOT IN (SELECT APP_ID FROM HISTORY WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') ='06.02.2009')
ORDER BY STORAGE_GB DESC )
WHERE ROWNUM <= 10
Oracle 将 rownum 应用于返回后的结果.
返回结果需要过滤,所以需要子查询.您还可以使用 RANK() 函数来获得 Top-N结果.
为了提高性能,请尝试使用 NOT EXISTS
代替 NOT IN
.请参阅this了解更多信息.
Oracle applies rownum to the result after it has been returned.
You need to filter the result after it has been returned, so a subquery is required. You can also use RANK() function to get Top-N results.
For performance try using NOT EXISTS
in place of NOT IN
. See this for more.
这篇关于Oracle SELECT TOP 10 记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Oracle SELECT TOP 10 记录
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01