MySQL遇见SELECT list is not in GROUP BY clause and contains nonaggre的问题
报错现象
执行SQL报错如下:
SELECT student.s_no,student.s_name,SUM(result.mark) FROM student,result WHERE student.s_no=result.s_no GROUP BY student.s_no
> 1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'db_ketest.student.s_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
> 时间: 0.081s
原因
MySQL5.7.5及以上版本有依赖检测功能。如果启用了ONLY_FULL_GROUP_BY SQL模式(默认开启),MySQL将拒绝选择列表,HAVING条件或ORDER BY列表的查询引用在GROUP BY子句中既未命名的非集合列,也不在功能上依赖于它们。(5.7.5之前,MySQL没有检测到功能依赖关系,默认情况下不启用ONLY_FULL_GROUP_BY。)
解决方法
方法一
使用命令行或者数据库客户端执行SQL
1.SQL语句,select @@global.sql_mode查询
mysql> select @@global.sql_mode;
+-------------------------------------------------------------------------------------------------------------------------------------------+
| @@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 |
+-------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.06 sec)
2.去掉ONLY_FULL_GROUP_BY,重新设置值
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';
方法二
vi修改MySQL配置文件my.cnf
[mysqld]
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服务:service mysql restart
End
林末 LinMo
★转载请注明出处及作者★