Mysql的distinct、order by和group by冲突报错
項目場景:
需求:前端下拉框(字段A)數據需要根據時間字段(字段B)倒序排序且去重返回(結果集是List<String>)
思路:1、distinct+order by;2、group by+order by;3、order by+java的set集合;4、先order by排序后distinct去重;
問題描述和分析
踩坑經歷:由于我本地數據庫的版本是5.7.35-log,項目發布線上數據庫版本是5.7.39,思路1和思路2在5.7.35-log版本都可運行,但是發布到5.7.39上就會報錯(思路1報錯:...which is not in SELECT list; this is incompatible with DISTINCT,思路2報錯:...which is not functionally dependent on columns in GROUP BY clause;)。
分析原因是:5.7.39版本的Mysql語法更加嚴格了,Distinct關鍵字也帶排序且優先級大于order by,且order by和group by后的字段在select中必須存在。
Mapper.java中顯示:
@Repository public interface ProcessExaminerMapper {List<String> getAllBatchByJudge(); }Mapper.xml中顯示:?
#思路1、distinct+order by <select id="getAllBatchByJudge" resultType="java.lang.String">SELECT DISTINCTbatch FROMst_process_examiner ORDER BYcreate_time DESC </select>#思路2、group by+order by <select id="getAllBatchByJudge" resultType="java.lang.String">SELECTbatch FROMst_process_examiner GROUP BYbatch ORDER BYcreate_time DESC </select>解決方案:
?解決方法:推薦思路4:先order by排序后distinct去重(一句sql解決,且速率快),
思路3可以用但不推薦,這里就不寫了,詳細思路:就是雙層for循環,外層循環是order by的有順序的list,內層循環是set集合,循環體操作:if判斷匹配元素,匹配到則插入一個新的list(返回的結果集合)并且set.remove("匹配的元素"),這樣做是為了減少內部循環次數
?Mapper.xml中顯示:
#思路4、先order by排序后distinct去重<select id="getAllBatchByJudge" resultType="java.lang.String">SELECT DISTINCTbatch FROM( SELECT DISTINCT batch, create_time FROM st_process_examinerORDER BY create_time DESC ) a </select>結束語:我們一生中可能只能決定5%的事情,決定不了出生、智商和貴人相助,但是沒有誰的劇本值得羨慕,只能把自己的劇本演好。
總結
以上是生活随笔為你收集整理的Mysql的distinct、order by和group by冲突报错的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2023最新SSM计算机毕业设计选题大全
- 下一篇: linux cmake编译源码,linu