这个报错是由于MySQL 5.7版本以后对于分组查询的规则进行了更改导致的。现在要求分组查询中选择的列必须要么出现在GROUP BY子句中,要么是聚合函数,否则会报错。如果数据表中存在要查询的字段中有出现在GROUP BY子句中的列之外的字段时,就会出现“Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated”的错误提示。
解决这个问题的方法有两个:一个是在MySQL配置文件中修改相关参数,另一个是修改查询语句。
方法1:修改MySQL配置文件
- 打开MySQL配置文件my.cnf,可以通过如下命令定位到配置文件路径:
# Ubuntu系统:
sudo vim /etc/mysql/my.cnf
# CentOS系统:
sudo vim /etc/my.cnf
- 在[mysqld]节下添加如下语句:
sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
- 修改完成后保存并退出配置文件,然后重启MySQL服务,使配置文件生效:
# Ubuntu系统:
sudo systemctl restart mysql
# CentOS系统:
sudo systemctl restart mariadb
方法2:修改查询语句
修改查询语句分两种情况:要么将查询语句中除了分组字段外的字段放入聚合函数中,要么将查询语句中多余的字段删掉。
情况一:将查询语句中除了分组字段外的字段放入聚合函数中。举例如下:
# 查询每个班级的平均成绩和学生总数,但是要求按照学生姓名的首字母排序,并且要显示班级名称以及学生姓名:
SELECT class_name, SUBSTRING(student_name, 1, 1) AS first_letter, AVG(score) AS avg_score, COUNT(*) AS count
FROM score INNER JOIN student ON score.student_id = student.id
GROUP BY class_name, first_letter
ORDER BY first_letter;
运行以上查询会出现错误提示“Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated,因为查询语句中的first_letter列既不是分组字段,也不是聚合函数。
正确的写法是将first_letter字段放到聚合函数中:
SELECT class_name, SUBSTRING(student_name, 1, 1) AS first_letter, AVG(score) AS avg_score, COUNT(*) AS count
FROM score INNER JOIN student ON score.student_id = student.id
GROUP BY class_name, SUBSTRING(student_name, 1, 1)
ORDER BY SUBSTRING(student_name, 1, 1);
情况二:将查询语句中多余的字段删掉。举例如下:
# 查询每个班级的平均成绩和学生总数,不需要显示班级名称和学生姓名:
SELECT AVG(score) AS avg_score, COUNT(*) AS count
FROM score INNER JOIN student ON score.student_id = student.id
GROUP BY class_name;
以上查询语句中的class_name字段是无关的,出现了错误提示“Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated”。正确的写法是将查询语句中不需要的class_name字段删掉:
SELECT AVG(score) AS avg_score, COUNT(*) AS count
FROM score INNER JOIN student ON score.student_id = student.id
GROUP BY class_name;
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:解决大于5.7版本mysql的分组报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated - Python技术站