关于sql:oracle数据库中的查询限制

Query limit in oracle database

本问题已经有最佳答案,请猛点这里访问。

我正在尝试创建具有某种限制的查询。

SELECT * FROM ALARMS WHERE OBJECT_ID=0 AND TIMESTAMP<=1525677504171 AND ROWNUM<=51 ORDER BY TIMESTAMP DESC

我使用rownum,但首先它设置了一个限制,然后选择ordered by。不过,我需要先订购,然后再限量。我发现在这里输入链接描述,我应该使用FETCH FIRST 51 ROWS ONLY。不幸的是,它不起作用。

1
SELECT * FROM ALARMS WHERE OBJECT_ID=0 AND TIMESTAMP<=1525677504171 ORDER BY TIMESTAMP DESC FETCH FIRST 51 ROWS ONLY;

它引发以下错误:

1
2
3
SQL Error [933] [42000]: ORA-00933: SQL command NOT properly ended

oracle.jdbc.OracleDatabaseException: ORA-00933: SQL command NOT properly ended


你只会在最后错过。如果我没记错的话,这个语法从12C R1开始就可用了。您使用哪种Oracle版本?

1
SELECT * FROM ALARMS WHERE OBJECT_ID=0 AND TIMESTAMP<=1525677504171 ORDER BY TIMESTAMP DESC FETCH FIRST 51 ROWS ONLY

编辑:

因为您的版本是11g,所以请尝试使用这种语法(我希望它可以工作;)

1
2
3
4
5
6
SELECT *
FROM (
    SELECT a.*,ROW_NUMBER() OVER(ORDER BY TIMESTAMP DESC) rcnt
    FROM ALARMS A WHERE OBJECT_ID=0 AND TIMESTAMP<=1525677504171) src  
WHERE src.rcnt <= 51
ORDER BY src.TIMESTAMP DESC;


FETCH FIRST仅在Oracle 12c之后可用。

对于rownum方法,使用包含order by的子查询,然后限制封闭查询中的行:

1
2
3
4
5
SELECT * FROM (
    SELECT * FROM ALARMS WHERE OBJECT_ID=0 AND TIMESTAMP<=152567750417
    ORDER BY TIMESTAMP DESC
) dt
WHERE ROWNUM<=51