oracle分頁查詢及rownum的使用____oracle

來源:互聯網
上載者:User
1,首先來說一下rownum的使用 rownum:對結果集加的一個偽列,即先查到結果集之後再加上去的一個列 (強調:先要有結果集),簡單的說 rownum 是對符合條件結果的序號。它總是從1開始排起的。所以你選出的結果不可能沒有1,而有其他大於1的值。
1,select int_id, zh_label, rownum rn from table_name where rownum <= 20; 正確 2,select int_id, zh_label, rownum rn from table_name where and rownum>10; 錯誤得不到結果
ROWNUM是一個序列,是為查詢結果添加序號。第一條記錄則rownum值為1,第二條為2,依次類推。如果你用>,>=,=,between...and這些條件,因為從結果集得到的第一條記錄的rownum為1,則被刪除,接著取下條,可是它的rownum還是1,又被刪除,依次類推,便沒有了資料;

有了以上從不同方面建立起來的對 rownum 的概念,那我們可以來認識使用 rownum 的幾種現像

  1). select rownum,c1 from t1 where rownum != 10 為何是返回前9條資料呢?它與 select rownum,c1 from tablename where rownum < 10 返回的結果集是一樣的呢?

  因為是在查詢到結果集後,顯示完第 9 條記錄後,之後的記錄也都是 != 10,或者 >=10,所以只顯示前面9條記錄。也可以這樣理解,rownum 為9後的記錄的 rownum為10,因條件為 !=10,所以去掉,其後記錄補上,rownum又是10,也去掉,如果下去也就只會顯示前面9條記錄了

  2). 為什麼 rownum >1 時查不到一條記錄,而 rownum >0 或 rownum >=1 卻總顯示所以的記錄

  因為 rownum 是在查詢到的結果集後加上去的,它總是從1開始

  3). 為什麼 between 1 and 10 或者 between 0 and 10 能查到結果,而用 between 2 and 10 卻得不到結果

  原因同上一樣,因為 rownum 總是從 1 開始 rownum不能以任何基表的名稱作為首碼;
例如 select int_id, zh_label, rownum rn from table_name a where  a.rownum <= 20;錯誤 select int_id, zh_label, rownum rn from table_name a where  rn <= 20;同樣不正確 2,分頁查詢SQL 1,無order by時,可以在第一層嵌套直接篩選一次 select *
  from (select int_id, zh_label, rownum rn
          from table_name
         where rownum <= 20) a
 where a.rn > 10;
2.當有order by時,會多一層嵌套 select *
  from (select a.*, rownum rn
          from (select int_id, zh_label
                  from table_name
                 where order by int_id) a
         where rownum <= 2 * 10) b
 where rn > 10;
這是因為 select int_id,zh_label,rownum from table_name where state=0 order by int_id;
此時的查詢結果第一條資料並不是以rownum開頭,主要原因是oracle是先提取記錄再排序的, 而oracle的rownum是在提取記錄就已經產生,它先於排序操作, 所以必須使用子查詢先排序,才能到得正確的結果  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.