当前位置:Gxlcms > mysql > 只需在orderby的字段上加主键或索引即可让oracle先按该字段排

只需在orderby的字段上加主键或索引即可让oracle先按该字段排

时间:2021-07-01 10:21:17 帮助过:47人阅读

SQL select rownum,t1. * from t1 where rownum 0 order by name desc; ROWNUM ID NAME ---------- ---------- -------------------- 2 2 yourlove 7 6 xifenfei 5 8 ting 6 7 really 4 4 game 8 5 feng 3 3 eygle 1 1 about 已选择8行。 SQL alter table t1

SQL> select rownum,t1. * from t1 where rownum >0 order by name desc;

ROWNUM ID NAME
---------- ---------- --------------------
2 2 yourlove
7 6 xifenfei
5 8 ting
6 7 really
4 4 game
8 5 feng
3 3 eygle
1 1 about

已选择8行。


SQL> alter table t1 add constraint pkKey primary key(name);

表已更改。

SQL> select rownum,t1. * from t1 where rownum >0 order by name desc;

ROWNUM ID NAME
---------- ---------- --------------------
1 2 yourlove
2 6 xifenfei
3 8 ting
4 7 really
5 4 game
6 5 feng
7 3 eygle
8 1 about

已选择8行。

SQL> select rownum,t1. * from t1 where rownum <3 order by name desc;

ROWNUM ID NAME
---------- ---------- --------------------
1 2 yourlove
2 6 xifenfei

SQL> select rownum,t1. * from t1 where id>2 and rownum <3 order by name desc;

ROWNUM ID NAME
---------- ---------- --------------------
1 6 xifenfei
2 8 ting

SQL> select rownum,t1. * from t1 where id>2 and rownum > 1 and rownum <3 order
by name desc;

未选定行

SQL>
注释:

rownum和order by哪个先执行,由优化器决定的。优化器根据具体情况决定他们俩的执行顺序:

一般先前者再后者。在order by 的字段上加主键或索引即可让oracle先按该字段排序,然后再rownum。

还有,有rownum的限制条件(如where子句里有rownum>2)在如where子句里,虽然where子句要早于rownum执行(rownum和order by都要晚于select子句执行,而select子句又晚于where子句执行),但是在where子句里面的rownum限制条件还是没有随着where子句执行而执行。


另见:《rownum的特点以及它与order by 子句的执行顺序关系

人气教程排行