原因:
1、首先,在MySQL中 distinct 的执行顺序高于 order by
2、第二,distinct 执行时会对查询的记录进行去重,产生一张虚拟的临时表
3、第三,order by 执行时对查询的虚拟临时表进行排序,产生新的虚拟临时表
因为order by 的字段不在select中,SQL语句执行distinct要优先于order by,distinct 去重之后的虚拟临时表中没有 order by后面的字段,所以在执行order by时会报错,所以 distinct 和order by 一起用时,order by的字段必须在select中。
SQL语句的执行顺序:
(1)from
(3) join
(2) on
(4) where
(5)group by(开始使用select中的别名,后面的语句中都可以使用)
(6) avg,sum.... (sql函数)
(7)having
(8) select
(9) distinct
(10) order by
(11)limit