現在一般對Oracle 分頁查詢實現如下
select * from (
select a.*,rownum r from (
自己的sql
) a where rownum <=?
) where r > ?
如果這個sql 按一個含有重複值的欄位排序
就會產生在不同頁查出重複記錄,並且某些記錄查不到的現象(不是一定產生)
測試代碼如下
CREATE TABLE TEST (
ID VARCHAR2(10) NOT NULL,
OD VARCHAR2(10) NULL
)
GO
--插入測試資料
insert into TEST
select level,case when level<=3 then level else null end from dual connect by level<=10
go
--測試分頁結果
第1-5條
select * from (
select a.*,rownum r from (
select t1.id from TEST t1
order by t1.od desc
) a where rownum <=5
) where r > 0
返回結果
行 ID R
1 4 1
2 8 2
3 7 3
4 6 4
5 5 5
第6-10條
select * from (
select a.*,rownum r from (
select t1.id from TEST t1
order by t1.od desc
) a where rownum <=10
) where r > 5
返回結果
行 ID R
1 6 6
2 5 7
3 3 8
4 2 9
5 1 10
可以看到第一個結果集中id=5和id=6 在第二個結果集中也查到了 同時id=9 和id=10的記錄都沒查到
解決方案如下
如果出現滿足上述兩個條件的SQL
order by 後再加上表的主鍵;
如本例中
改為order by t1.od desc,t1.id 後現象消失
如果有更好的解決方案, 希望能告知= =
更多Oracle相關資訊見Oracle 專題頁面 http://www.bkjia.com/topicnews.aspx?tid=12