【SQL】Group by 和Order By 後字段不一致引起的錯誤ORDER BY clause is not in GROUP BY clause

一、問題

1.1、環境
電腦環境:Windows 10;
開發工具:IntelliJ IDEA;
數據庫環境:Redis 3.2.100
JDK環境: Jdk1.8;

1.2、問題

java.sql.SQLSyntaxErrorException: Expression #1 of ORDER BY clause is not in GROUP BY clause and contains 
nonaggregated column 'a.create_time' which is not functionally dependent on columns in GROUP BY clause; 
this is incompatible with sql_mode=only_full_group_by

二、解答

這裏,有的同學會以爲是sql_mode的問題,然後去改sql_mode的配置文件;

其實不是,我們仔細看報錯的日誌,首先總覽全文,是SQL格式錯誤異常;其次說了第一個參數(根據Expression #1得知),Order by 的從句不在Group by從句之中,並且包含非聚合的字段create_time,這個字段不是group by 從句的功能性依賴;

		<!--省略了前面的SQL-->
        GROUP BY
        (
        date_format(a.create_time, '%Y-%m-%d')
        )
        ORDER BY a.create_time asc

所以,通過觀察得知,Mysql編譯器認爲,我們的order by 從句後面的字段,不是group by 從句中的字段,將他們判定爲2個字段,所以報錯;我們只要將兩個字段的格式改成一樣的即可:

        GROUP BY
        (
        date_format(a.create_time, '%Y-%m-%d')
        )
        ORDER BY date_format(a.create_time, '%Y-%m-%d')  asc

完畢~

三、總結

歡迎關注我的
CSDN博客: https://blog.csdn.net/River_Continent
微信公衆號:幕橋社區
在這裏插入圖片描述
知乎:張牧野, https://www.zhihu.com/people/zhang-mu-ye-37-76/activities
簡書: https://www.jianshu.com/u/02c0096cbfd3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章