ORA-01791:not a SELECTed expression

來源:互聯網
上載者:User

 

問題出現的原因:

 

  There is an incorrect ORDER BY item. The query is a SELECT DISTINCT query with an ORDER BY clause. In this context, all ORDER BY items must be constants, SELECT list expressions, or expressions whose operands are constants or SELECT list expressions.

 

 大致就是說select distinct 和order by一起使用的時候,order by中必須是常量或者select列表中出現的運算式。

 

 例如: select distinct  t.name from user t  order by t.modified_date ASC

 

這樣就會出現錯誤。

 

 

其實上面的說法不完全正確。對於單表來講,如果name這個欄位有unique index 並且欄位有not null約束。那麼這條語句是不會出錯的。

 

如果是多個表join,這種情況我經過大量測試,發現仍然會出錯,所以這種特殊性目前看來只存在於單表中。使用中大家注意。

 

至於為什麼會出現這種特殊性,其他的要出錯,而唯獨滿足以上紅色部分條件不錯,原因大概是這樣的:

 

 假設name不唯一,返回時存在如下三條記錄

  name   modified_date

   A          2008-11-12

   A          2008-11- 14

   B          2008-11-13

 

    執行distinct 後得到 A 、B (注意,這裡沒有管順序),然後根據modified_date欄位來確定A、B記錄的先後順序,這個時候問題就來了,order by根據哪個modified_date來排序來確定A的位置呢?如果根據第一個,那麼結果應該是AB,根據第二個結果應該是BA,確定不了了。。。。所以當然會報錯。

 

如果name唯一,查詢出來的記錄即使不distinct也是唯一的,這一點資料庫自己是明白的,那麼order by時,當然可以排出序來。這樣就不會出錯。

 

所以不管是單表還是多表,只要oracle自己區分不出根據哪個來排序就會出現這個異常。

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.