问题
做项目过程时,遇到hibernate实现分页功能中,在不同页面有存在重复数据。一开始以为是hibernate的问题,打开hibernate的show_sql=true开启,将生成的sql在plsql中执行复现了数据重复的问题。查阅资料得知,oracle在保证order by字段的排序外,相同order by字段的值不同记录之间排序顺序并不稳定。
比如表a
id | score |
1 | 5 |
2 | 10 |
3 | 10 |
4 | 20 |
oracle常见的分页sql查询的前两条的记录
select id,score,rownum rn from (select * from a order by score) where rownum<=2
结果1为
id | score |
1 | 5 |
2 | 10 |
select id,score from (select id,score,rownum rn from (select * from a order by score) where rownum<=4) where rn>2
结果2为
id | score |
2 | 10 |
4 | 20 |
出现这种情况因为oracle排序算法的不稳定。
解决方案
再不影响现有排序效果下,增加唯一排序字段,比如主键或者rowid等字段。