排序的迷惑

action929發表於2007-08-01
排序的迷惑,請教!

create table cust
( cust_id number(10),
cust_name varchar2(50)
)
;
insert into cust values(1 ,'aaa');
insert into cust values(2 ,'bbb');
insert into cust values(3 ,'ccc');
insert into cust values(4 ,'ddd');
insert into cust values(5 ,'eee');

====
SQL> select * from (
2 SELECT cust_name,MAX(cust_id) OVER ( order by cust_id desc ) cc
3 FROM cust) where rownum=1
4 /

CUST_NAME CC
------------------ ----------
eee 5

SQL> select cust_name from (
2 SELECT cust_name,MAX(cust_id) OVER ( order by cust_id desc ) cc
3 FROM cust) where rownum=1
4 /

CUST_NAME
------------------
aaa

迷惑,為什麼結果不一樣?

[@more@]

SQL> set autotrace on
SQL> select * from (
2 SELECT cust_name,MAX(cust_id) OVER ( order by cust_id desc ) cc
3 FROM cust)
4 /
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 VIEW
2 1 WINDOW (SORT)
3 2 TABLE ACCESS (FULL) OF 'CUST'

SQL> select cust_name from (
2 SELECT cust_name,MAX(cust_id) OVER ( order by cust_id desc ) cc
3 FROM cust)
4 /
Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 VIEW
2 1 TABLE ACCESS (FULL) OF 'CUST'

原因自然是由於執行計劃的不同,但是為什麼會導致執行計劃的不同,我只能認為,當你沒有訪問那個要排序的列的時候,oracle很聰明的識別出來了,然後內部做處理了,導致資料沒有按照你想象的去排序。

其實用:

SQL> select cust_name from (
2 SELECT cust_name,cust_id
3 FROM cust order by cust_id desc)
4 /

CUST_NAME
--------------------------------------------------
eee
ddd
ccc
bbb
aaa


Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 VIEW
2 1 SORT (ORDER BY)
3 2 TABLE ACCESS (FULL) OF 'CUST'

就可以了,為啥要那麼複雜呢。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/133835/viewspace-929885/,如需轉載,請註明出處,否則將追究法律責任。

相關文章