mysql:报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonag

Posted ABin-阿斌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql:报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonag相关的知识,希望对你有一定的参考价值。

声明:

  • 原文作者【CSDN】:lankun66
  • 原文地址:https://blog.csdn.net/qq_44625080/article/details/104043682

前言

  • 最新在开发中遇到了一个问题,就是在代码书写中我用了 GroupBy做去重处理。在开发环境测试是好的,但是发布到测试就报了如下错误。
  • 报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre
  • 后来问运维兄弟才知道:测试环境的 mysql 升级了:5.7.38版本
  • 下面就是问题原因,大家可以参考一下。处理方法很简单,叫运维兄弟修改一下配置文件,重启mysql 即可。

1.描述:

数据库中的表grades为

id	 |	gro	| name	| score
---------------------------
1	 |	A	| 张三	| 20
2	 |	B	| 李四	| 19
3	 |  B	| 王五	| 17
4	 |  C	| 赵六	| 18

SQL语句

select name, gro from grades group by gro

返回

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘grades.name’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

同样的SQL语句,在mysql5.5.43的数据库中报错,在5.7.5的mysql数据库中却正常。

2.分析

对于上述的报错信息,在下的理解是select字段里包含了没有被group by条件唯一确定的字段name。

因为执行sql_make_group语句实际上把两行纪录李四和王五合并成一行,搜索引擎不知道该返回哪一条,所以报错。

3.原因:

MySQL 5.7.5后only_full_group_by成为sql_mode的默认选项之一,这可能导致一些sql语句失效。

4.解决方法:

vim /etc/mysql/conf.d/mysql.cnf

在配置文件my.cnf中关闭sql_mode=ONLY_FULL_GROUP_BY.。msqyl的默认配置是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去掉,也可以去掉所有选项设置成sql_mode=,如果你确信其他选项不会造成影响的话

复制并粘贴,如有[mysqld],则放到 [mysqld]最后,如没有则放到配置文件最下方即可

[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

wq保存并退出

重启MySQL

  • service mysql restart

以上是关于mysql:报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonag的主要内容,如果未能解决你的问题,请参考以下文章

windows server 2008 安装MySQL 8.0 遇到报错 1055 - Expression #1 of ORDER BY clause is not in GROUP BY(示例代

MYSQL报错:1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated col

mysql报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre

mysql:报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonag

mysql报错Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column问题(示例

mysql报错Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column问题(示例