1. 程式人生 > >mysql SELECT list is not in GROUP BY clause and contains nonaggregated column

mysql SELECT list is not in GROUP BY clause and contains nonaggregated column

安裝了mysql5.7,用group by 查詢時丟擲如下異常:

Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'userinfo.t_long.user_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

原因:       MySQL 5.7.5和up實現了對功能依賴的檢測。如果啟用了only_full_group_by SQL模式(在預設情況下是這樣),那麼MySQL就會拒絕選擇列表、條件或順序列表引用的查詢,這些查詢將引用組中未命名的非聚合列,而不是在功能上依賴於它們。(在5.7.5之前,MySQL沒有檢測到功能依賴項,only_full_group_by在預設情況下是不啟用的。關於前5.7.5行為的描述,請參閱MySQL 5.6參考手冊。)

執行以下個命令,可以檢視 sql_mode 的內容。

mysql> SHOW SESSION VARIABLES;
mysql> SHOW GLOBAL VARIABLES;
mysql> select @@sql_mode;

可見session和global 的sql_mode的值都為:  ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

only_full_group_by說明:  only_full_group_by :使用這個就是使用和oracle一樣的group 規則, select的列都要在group中,或者本身是聚合列(SUM,AVG,MAX,MIN) 才行,其實這個配置目前個人感覺和distinct差不多的,所以去掉就好 

解決:

執行以下兩個命令:

mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

---------------------  轉載:https://blog.csdn.net/fansili/article/details/78664267