ORA-01791: 不是 SELECTed 表达式

ORA-01791: 不是 SELECTed 表达式

在使用Oracle11g的时候,在执行一条查询语句的时候,报了如题的错误,这条SQL的本意是查询一个去重的列表,并按照数据的优先级进行排序,举个栗子:

select distinct name from student order by grade desc

乍一看没什么问题,但是查询了资料之后才发现,StackOverflow中是这样解释的:

The problem here is the ORDER BY column TITLE isn’t selected in the DISTINCT query. Since DISTINCT is used, the SELECT query will try to group the resultset based on the selected columns.ORDER BY column isn’t selected here, it doesn’t ensure the uniqueness on the resultset and hence it fails to apply ORDER BY.

问题的原因是我们在排序中使用的字段不包含在distinct查询的结果中,因为使用了distinct,所以查询语句会尝试基于查询的列将结果集分组,order by的列没有被查询,所以不能保证结果集的唯一性所以排序失败。
拿上面的例子进行修改,修改后的SQL如下:

select distinct name, grade from student order by grade desc

这样就可以了,只要在需要排序的时候把排序字段也查询出来就可以避免这样的错误了。
欢迎指正

猜你喜欢

转载自blog.csdn.net/TsuiXh/article/details/86607661