Oracle關鍵字rownum的使用

2021-09-01 15:46:46 字數 1857 閱讀 5838

rownum是oracle提供的乙個偽列,我們用的比較多的地方是在做分頁的時候。

如果對rownum使用不當,往往會出現一些比較抓狂的現象。

假如有表結構如下:

tid  tname ttype

5    t1    q1

4    t4    q1

3    t3    q7

2    t2    q2

1    t1    q6

6    t6    q1

7    t7    q3

8    t8    q3

9    t9    q4

10    t10    q5

執行語句:select rownum,t.* from t_test t order by t.tid;

預期的結果應該是:

rownum tid tname ttype

1    1    t1    q6

2    2    t2    q2

3    3    t3    q7

4    4    t4    q1

5    5    t1    q1

6    6    t6    q1

7    7    t7    q3

8    8    t8    q3

9    9    t9    q4

10    10    t10    q5

而真實結果確實:

rownum tid tname ttype

5    1    t1    q6

4    2    t2    q2

3    3    t3    q7

2    4    t4    q1

1    5    t1    q1

6    6    t6    q1

7    7    t7    q3

8    8    t8    q3

9    9    t9    q4

10    10    t10    q5

產生的結果並沒有按我們預期的先排序再生成rownum值,生成的rownum值是按照我們新增資料時的順序。

產生這種結果可以有兩種方式解決:

1、order by 字段建立主鍵約束

2、將rownum提到外層使用,語句:

select rownum,tt.* from (

select * from t_test t

)tt採用這兩種方式之一,輸出的結果就同我們預想的一樣。

但是,在使用的過程中發現了另外乙個問題,在對分組字句使用rownum時顯示亂序。

sql語句:

select * from (

select max(t.tid),max(t.tname),t.ttype from t_test t group by t.ttype

) tt where rownum<3

執行結果並沒有如預期顯示子查詢結果的前兩行資料。

解決方法有兩個:

1、分組內部先排序

select * from (

select max(t.tid),max(t.tname),t.ttype from t_test t group by t.ttype order by max(t.tid)

) tt where rownum<3

2、分組外多包層查詢

select ttt.* from (

select rownum row_num,tt.* from (

select max(t.tid),max(t.tname),t.ttype from t_test t group by t.ttype

) tt

) ttt where rownum<3

ORACLE 常用關鍵字

1.siblings siblings 是兄弟姐妹的意思,那麼order siblings by的意思就是在兄弟姐妹之間的排序,和order by所表示的含義絕對不同,針對樹狀sql,我覺得order siblings by更有意義,樹狀sql查詢出來的結果本身就是按照層次 hierarchy 結構...

new關鍵字 this關鍵字 base關鍵字

使用new,所做的三件事 1.類是引用物件,引用物件是在堆中開闢空間 在堆中開闢空間 2.在開闢的堆空間中建立物件 3.呼叫物件的構建函式 4.隱藏父類成員 子類的成員可以與隱藏從父類繼承的成員,類似於重寫。public new void sayhello this關鍵字的使用 1.代表當前類的物件...

this關鍵字 static關鍵字

1.當成員變數和區域性變數重名,可以用關鍵字this來區分 this 代表物件,代表那個物件呢?當前物件 this就是所在函式所屬物件的引用 簡單說 那個物件呼叫了this所在的函式,this就代表哪個物件 this也可以用於在建構函式中呼叫其他建構函式 注意 只能定義在建構函式的第一行,因為初始化...