一、报错
sql语句:select DISTINCT type from bill_mes order by create_time;
Expression #1 of ORDER BY clause is not in SELECT list, references column 'bear_bill.bill_mes.create_time' which is not in SELECT list; this is incompatible with DISTINCT
翻译:ORDER BY子句的表达式#1不在SELECT列表中,引用了不在SELECT名单中的列“bear_bill.mes.create_time”;这与DISTINCT不兼容
二、报错原因
原因总结如下:
第一,在mysql中distinct 的执行顺序高于order by。
第二,distinct执行时会对查询的记录进行去重,产生一张虚拟的临时表;
第三,order by执行时对查询的虚拟临时表进行排序,产生新的虚拟临时表。
综合来看,如果order by的字段不在select中,执行sql语句时首先执行distinct,之后产生的虚拟临时表中没有order by的字段,所以再执行order by时会报错。
三、解决方法
可以使用下面方式实现去重排序功能:
sql语句:select type from bill_mes GROUP BY type ORDER BY MAX(create_time);
四、参考
Sql中DIstinct与Order By同时使用问题_Sql中DIstinct与Order By同时使用问题_404技术社区