簡體   English   中英

從 SQL 查詢 Oracle 中檢索一系列記錄

[英]Retrieve a range of records from SQL query Oracle

我有這個 Java 代碼用於 JSF 分頁:

public List<ActiveSessionObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws Exception {

        String SQL_LIST_BY_ORDER_AND_LIMIT = "SELECT * FROM ACTIVESESSIONSLOG ORDER BY ? ? LIMIT ?, ?";



        if (ds == null) {
            throw new SQLException();
        }

        String sortDirection = sortAscending ? "ASC" : "DESC";
        String sql = String.format(SQL_LIST_BY_ORDER_AND_LIMIT, sortField, sortDirection);
        Connection conn = ds.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<ActiveSessionObj> dataList = new ArrayList<ActiveSessionObj>();

        try {
            conn.setAutoCommit(false);
            boolean committed = false;
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, sortField);
            preparedStatement.setString(2, sortDirection);
            preparedStatement.setInt(3, firstRow);
            preparedStatement.setInt(4, rowCount);

            resultSet = preparedStatement.executeQuery();
            /* take the result from the SQL query and insert it into Array List collection */
            dataList = ActiveSessionsArrayList(resultSet);

        } catch (SQLException e) {
            throw new Exception(e);
        } finally {
            conn.close();
        }

        return dataList;
    }

我使用這個 SQL 語句生成 ArrayList:

SELECT * FROM ACTIVESESSIONSLOG ORDER BY ? ? LIMIT ?, ?

這個 SQL 查詢可以用於 Oracle 嗎? 或者這是 MySQL 特定的?

最良好的祝願

LIMIT特定於 MySQL。 但是,在 Oracle 中,您可以像這樣使用rownum

SELECT *
FROM (SELECT columnA, columnB, rownum as my_rownum
FROM ACTIVESESSIONSLOG
ORDER BY ? ?) 
WHERE my_rownum <= ? 
AND my_rownum >= ? 
Case1: If you want first `twenty Records` only then 

 select * from ( 
     select rn,a.*
     from Activesessionlogs a
     order by ??)
 where rn <=20
 order by rn

Case2:If you want the record between `5 to 10` then

select * from (
select rownum rn,e.* from Activesessionlogs e order by ??)
where rn >=5 and rn<=10 
order by rn 

例如:讓我們在下面找到一個例子

select * from (
select rownum rn,e.* from emp e order by hiredate)
where rn >=5 and rn<=10
order by rn asc

輸出

注意Rownum> or rownum>=不會在同一個查詢中工作。一個很好的博客解釋了這個Oracle Rownum

不幸的是,LIMIT 在 oracle 中不是有效語句,它在 MySql 中使用。但是 oracle 有一個變量 ROWNUM,您可以使用它來限制返回的行數:

select * from mytable where rownum <= 100 and rownum > 50

從您的查詢中返回第二個 50 條記錄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM