not a SELECTed expression

来源:互联网 发布:成都菜鸟网络招聘 编辑:程序博客网 时间:2024/06/06 00:36

异常信息:

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. 
   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自己区分不出根据哪个来排序就会出现这个异常。

原创粉丝点击