1. 程式人生 > >Oracle中的order by分頁排序問題

Oracle中的order by分頁排序問題

今天在系統測試的過程中,測試人員發現自己新新增的科目新增到系統中在頁面預設分頁查詢中沒有找到自己新加的科目(分頁過程中頁面顯示資料確實和資料表中的資料總量一致),但是通過系統的搜尋功能是可以查詢的到資料?提了一個bug?

解決bug的過程:

系統中有一個科目表subject_manage表結構如下

create table SUBJECT_MANAGE
(
  ID          VARCHAR2(32) not null,
  SUBJECTNAME VARCHAR2(50),
  EXAMTASKID  VARCHAR2(32),
  EXAMTYPE    VARCHAR2(100)
)
comment on table SUBJECT_MANAGE
  is '用於高考、成考、自考等考試型別的科目日常管理。';
-- Add comments to the columns 
comment on column SUBJECT_MANAGE.SUBJECTNAME
  is '科目名稱';
comment on column SUBJECT_MANAGE.EXAMTASKID
  is '考試型別ID';
comment on column SUBJECT_MANAGE.EXAMTYPE
  is '考試型別名稱';
comment on column SUBJECT_MANAGE.STARTTIME
分頁sql的語句為
<pre name="code" class="sql">select * from ( select row_.*, rownum rownum_ from (  select id,subjectname,examtaskid, examtype  from subject_manage where 1=1   order by examtype ) row_ where rownum <= index * pagesize) table_alias where table_alias.rownum_ >= (index - 1) * pagesize + 1

當頁面分頁到index=3或index=4的時候就出現了重複資料,當時檢視subject_manage表中的examtype欄位有空值,當時就懷疑會不會是空欄位引起的問題,就換了表中的id為排序欄位,測試果然好使,之後就將examtype欄位中為空的行填充一個預設值,再進行查詢還是有重複欄位

examtype 列並不能確定其唯一性,那麼ORACLE在每次執行排序時並不能確定資料的唯一性,導致同樣的排序順序但是每次執行時並不能保證得到一樣的結果。

解決辦法

select * from ( select row_.*, rownum rownum_ from (  select id,subjectname,examtaskid, examtype  from subject_manage where 1=1   order by examtype,id ) row_ where rownum <= index * pagesize) table_alias where table_alias.rownum_ >= (index - 1) * pagesize + 1
有以上的結論之後處理方法也就簡單明瞭了,Order By中的欄位必須能夠確保唯一即可