我有这个用于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特定的?
祝福
答案 0 :(得分:3)
LIMIT
是MySQL特有的。但是在Oracle中,您可以使用rownum
,如下所示:
SELECT *
FROM (SELECT columnA, columnB, rownum as my_rownum
FROM ACTIVESESSIONSLOG
ORDER BY ? ?)
WHERE my_rownum <= ?
AND my_rownum >= ?
答案 1 :(得分: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
答案 2 :(得分:1)
不幸的是,LIMIT不是oracle中的有效语句,它在MySql中使用。但是,oracle有一个变量ROWNUM,您可以使用它来限制返回的行数:
select * from mytable where rownum <= 100 and rownum > 50
从您的查询中返回第二个50条记录。