2

我有这个用于 JSF 分页的 Java 代码:

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 的?

最良好的祝愿

4

3 回答 3

3

LIMIT是特定于 MySQL 的。但是在 Oracle 中,您可以rownum这样使用:

SELECT *
FROM (SELECT columnA, columnB, rownum as my_rownum
FROM ACTIVESESSIONSLOG
ORDER BY ? ?) 
WHERE my_rownum <= ? 
AND my_rownum >= ? 
于 2012-04-08T12:50:18.087 回答
3
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

于 2012-04-08T13:42:51.780 回答
1

不幸的是 LIMIT 不是 oracle 中的有效语句,它在 MySql 中使用。但是 oracle 有一个变量 ROWNUM 可以用来限制返回的行数:

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

从您的查询中返回后 50 条记录。

于 2012-04-08T12:52:23.380 回答