1.在ORACLE中实现SELECT TOP N
由于ORACLE不支持SELECT TOP语句,所以在ORACLE中经常是用ORDER BY跟ROWNUM的组合来实现SELECT TOP N的查询。
SELECT 列名1...列名n FROM
(
SELECT 列名1...列名n FROM 表名 ORDER BY 列名1...列名n
)
WHERE ROWNUM <= N(抽出记录数)
ORDER BY ROWNUM ASC
SQL> select rownum, hs_login from
(
select hs_login from t_users order by hs_login
)
where rownum < 5 order by rownum desc;
ROWNUM HS_LOGIN
---------- --------------------------------------------------
4 admin101
3 admin100
2 admin10
1 admin1
Elapsed: 00:00:00.03
2.在TOP N纪录中抽出第M(M <= N)条记录
ROWNUM是记录表中数据编号的一个隐藏子段,所以可以在得到TOP N条记录的时候同时抽出记录的ROWNUM,然后再从这N条记录中抽取记录编号为M的记录,即使我们希望得到的结果。
SELECT 列名1...列名n FROM
(
SELECT ROWNUM RN, 列名1...列名n FROM
(
SELECT 列名1...列名n FROM 表名 ORDER BY 列名1...列名n
)
WHERE ROWNUM <= N(抽出记录数)
ORDER BY ROWNUM ASC
)
WHERE RN = M(M <= N)
SQL> select rownum, hs_login, hs_nick_name from
(
select rownum rn, hs_login, hs_nick_name from
(
select hs_login, hs_nick_name from t_users order by hs_login
)
where rownum < 5
order by rownum desc
)
where rn = 3;
ROWNUM HS_LOGIN HS_NICK_NAME
---------- ------------- --------------
1 admin100 Lcr Admin
Elapsed: 00:00:00.08
3.抽出从第M条记录开始的X条记录
SELECT 列名1...列名n FROM
(
SELECT ROWNUM RN, 列名1...列名nFROM
(
SELECT 列名1...列名n FROM 表名 ORDER BY 列名1...列名n)
)
WHERE ROWNUM <= N (N = (M + X - 1))
ORDER BY ROWNUM ASC
)
WHERE RN >= M
SQL> select rownum, hs_uuid, hs_login from
(
select rownum rn, hs_uuid, hs_login from
(
select hs_login, hs_uuid from t_users order by hs_uuid
)
where rownum < 800
order by rownum desc
)
where rn > 790;
ROWNUM HS_UUID HS_LOGIN
---------- ---------- --------------------------------------------------
1 799 admin799
2 798 admin798
3 797 admin797
4 796 admin796
5 795 admin795
6 794 admin794
7 793 admin793
8 792 admin792
9 791 admin791
9 rows selected.
Elapsed: 00:00:00.12
注意:
当我们order by时的字段为hs_login的话并没有达到我们希望的效果,即便是我给字段hs_login添加了索引。但是,当我使用主键hs_uuid时,可以取到我们希望的数据。
这里需要进一步的学习来得出结论,暂时不知其原因。
<<OVER>>