【MySQL distinct的使用】如果指定了 SELECT DISTINCT,那么 ORDER BY 子句中的项就必须出现在选择列表中
錯(cuò)誤語句
SELECT distinct example_column1 FROM test.example_table where delisting_date>now() and product ='CU.SHF' ORDER BY `example_column2` ASC;報(bào)錯(cuò)信息如下:(MySQL-8.0.16可以正常運(yùn)行,MySQL-5.7報(bào)錯(cuò))
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;查詢結(jié)果
原因解釋
MySQL中,如果同時(shí)用order by和distinct,那order by后面的字段就必須出現(xiàn)在selcet的字段中。
為什么會(huì)出現(xiàn)這種情況?我們來看下原因:
distinct自帶排序功能,會(huì)先按照distinct后面的字段進(jìn)行排序,而order by是可以改變distinct自帶的排序,所以原因其實(shí)就是一個(gè)執(zhí)行先后順序問題,沒有distinct時(shí),order by先執(zhí)行,select后執(zhí)行,有了distinct,selcet distinct先執(zhí)行,order by后執(zhí)行,如果select distinct執(zhí)行完后,去除了相應(yīng)字段,所以order by就沒法排序了。
如果你不明白distinct是怎么排序和去重復(fù)的,去看下SQL的執(zhí)行計(jì)劃就明白了。
總結(jié)
以上是生活随笔為你收集整理的【MySQL distinct的使用】如果指定了 SELECT DISTINCT,那么 ORDER BY 子句中的项就必须出现在选择列表中的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Git】切换分支,以及git stas
- 下一篇: 【MySQL】如何让数据库查询区分大小写