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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值