【MySQL distinct的使用】如果指定了 SELECT DISTINCT,那么 ORDER BY 子句中的项就必须出现在选择列表中

错误语句

SELECT distinct example_column1 FROM test.example_table where delisting_date>now() and product ='CU.SHF' ORDER BY `example_column2` ASC;

报错信息如下:(MySQL-8.0.16可以正常运行,MySQL-5.7报错)

Error Code: 3065. Expression #1 of ORDER BY clause is not in SELECT list, references column ‘test.example_table.example_column2’ which is not in SELECT list; this is incompatible with DISTINCT 0.016 sec

正确语句

SELECT distinct example_column1, example_column2 FROM test.example_table where delisting_date>now() and product ='CU.SHF' ORDER BY `example_column2` ASC;

查询结果
在这里插入图片描述

原因解释

MySQL中,如果同时用order by和distinct,那order by后面的字段就必须出现在selcet的字段中。

为什么会出现这种情况?我们来看下原因:

distinct自带排序功能,会先按照distinct后面的字段进行排序,而order by是可以改变distinct自带的排序,所以原因其实就是一个执行先后顺序问题,没有distinct时,order by先执行,select后执行,有了distinct,selcet distinct先执行,order by后执行,如果select distinct执行完后,去除了相应字段,所以order by就没法排序了。

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

发布了552 篇原创文章 · 获赞 201 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/103616076