如果指定了 SELECT DISTINCT,那么 ORDER BY 子句中的项就必须出现在选择列表中。(解决方法及原因分析)

解决办法:sqlserver中如果同时用order by和distinct,那order by后面的字段就必须出现在selcet的字段中。这个问题只有在sqlserver中才会有,mysql中是不会有这个问题的。


如果这样写会提示错误:
select distinct name from user order by id

应该这样写:
select distinct id,name from user order by id


为什么会出现这种情况?我们来看下原因:
distinct自带排序功能,会先按照distinct后面的字段进行排序,而order by是可以改变distinct自带的排序,所以原因其实就是一个执行先后顺序问题,没有distinct时,order by先执行,select后执行,有了distinct,selcet distinct先执行,order by后执行,如果select distinct执行完后,去除了相应字段,所以order by就没法排序了。


如果你不明白distinct是怎么排序和去重复的,去看下SQL的执行计划就明白了。

猜你喜欢

转载自blog.csdn.net/m0_37679452/article/details/79878980