mysqldistinct和orderby⼀起⽤时,orderby的字段必须在select中
mysql中distinct和order by ⼀起⽤时,order by的字段必须在select中
mysql 5.7.14
SELECT DISTINCT evt_tim FROM evt_etl ORDER BY evt_id ASC;
执⾏报错Unknown error 3065。
因为不到3065错误的详细信息,因此做了⼀下测试:
- 1.SELECT DISTINCT evt_id FROM evt_etl ORDER BY evt_id ASC;
- 2.SELECT DISTINCT evt_tim,evt_id FROM evt_etl ORDER BY evt_id ASC;
distinct查询- 3.SELECT evt_tim FROM evt_etl ORDER BY evt_id ASC;
1,2,3 这三条语句均执⾏正确。
mysql distinct和order by ⼀起⽤时,order by的字段必须在select中。
⽹上查了⼀下资料,原因总结如下:
⾸先,在mysql中distinct 的执⾏顺序⾼于order by。
第⼆,distinct执⾏时会对查询的记录进⾏去重,产⽣⼀张虚拟的临时表;
第三,order by执⾏时对查询的虚拟临时表进⾏排序,产⽣新的虚拟临时表。
综合来看,如果order by的字段不在select中,执⾏sql语句时⾸先执⾏distinct,之后产⽣的虚拟临时表中没有order by的字段,所以再执⾏order by时会报错。