java 取结果集的最后三项,
数据库是oracle 10G
我现在插入数据:
insert into you (id,name) values (1,'john1');
insert into you (id,name) values (2,'john2');
insert into you (id,name) values (3,'john3');
insert into you (id,name) values (4,'john4');
insert into you (id,name) values (5,'john5');
我想取最后三条记录,
3 john3
4 john4
5 john5
这个怎么实现呢? 请指教
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "zhang",
"zhang");
stmt = conn.createStatement();
String url = "select * from you where rownum<=3 order by id desc";
我这里只能取到前三条,取不了后三条,
rs = stmt.executeQuery(url);
while (rs.next()) {
out.print(rs.getString("id"));
out.print(rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案1:
SELECT * FROM (SELECT * FROM you ORDER BY id DESC ) WHERE ROWNUM<=3;
如果ID是自增的,这样应该是可以的。
答案2:
应该是一个分页查询的问题
select id,name from (select id,name,rownum rn from you where rownum <= (select count(*) from you)) where rn > (select count(*) from you)-3;
最后 -3 是取数据表的最后3条,-n就是取最后几条