Oracle 分頁查詢 重複資料的問題

來源:互聯網
上載者:User

現在一般對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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.