MySQL解决报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

报错信息及语句如下

我这个语句是因为我偷懒是不规范的group by用法, 当然偷懒是不对的,所以我最后使用了不偷懒的写法。

select id, count(type) ,type from menu where big_type ='豆科' group by type;
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated 
column 'rent.menu.id' which is not functionally dependent on columns in GROUP BY clause;
 this is incompatible with sql_mode=only_full_group_by

MySQL解决报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column_第1张图片


原因分析:

使用GROUP BY 语句违背了 sql_mode=only_full_group_by,mysql5.7以后自动开启了 only_full_group_by服务,只要关了就行。

查看官方文档,发现从 MySQL 5.7.5 开始,默认 SQL 模式包括 ONLY_FULL_GROUP_BY。 (在 5.7.5 之前,MySQL 不检测函数依赖,并且默认不启用 ONLY_FULL_GROUP_BY)这可能会导致一些sql语句失效。


解决方案:

1. 永久有效(修改配置文件)

Windows 用户

编辑 mysql 配置文件 my.ini,在尾部添加以下内容,重新启动 mysql 即可:
我的是C:\ProgramData\MySQL\MySQL Server 8.0\my.ini

[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

MySQL解决报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column_第2张图片

注意:配置完my.ini文件后 点击文件另存为, 将编码格式设置为ANSI格式, 然后保存在mysql根目录下
MySQL解决报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column_第3张图片
重启mysql

启动
net start mysql80
停止
net stop mysql80

2. 扩展:临时有效

查看当前的sql_mode

SELECT @@GLOBAL.sql_mode;
或用
show variables like 'sql_mode';

结果:

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

然后只要设置这个属性吧开头的ONLY_FULL_GROUP_BY去掉就完事了。

SET sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

MySQL解决报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column_第4张图片

PS:这样修改只是这一次会话有效,要永久有效还是修改配置文件吧。

你可能感兴趣的:(mysql,mysql,数据库)