赞
踩
排错-解决MySQL非聚合列未包含在GROUP BY子句报错问题
By:授客QQ:1033553122
测试环境
win10
MySQL 5.7
问题描述:
执行类似以下mysql查询,
SELECT id, name, count(*) AS cnt FROM case_table GROUP BY name
报错,如下:
服务器内部错误 (1055, "Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'case_table.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by")
原因:存在非聚合列 id ,没有包含在GROUP BY子句中。
但是本例中,其它地方需要用到这个id列,不能去掉,那咋办呢?如下
解决方法
方法1
查询全局sql_mode
SELECT @@GLOBAL.sql_mode;
或者
SELECT @@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';
SET SESSION
复制查询结果,然后设置GLOBAL sql_mode,SESSION sql_model为查询结果去掉 “ONLY_FULL_GROUP_BY,”的值,如下:
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';
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后,以上设置失效。
方法2
启动mysql时,增加sql_model选项,如下:
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" [...其它选项]
方法3:
linux服务下,修改my.conf (Windows下修改my.ini),在[mysqld]节点下,最末尾添加sql_mode配置,如下:
...
[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
[其它节点配置]
...
标签:GROUP,NO,MySQL,排错,ZERO,报错,mode,sql,DATE
来源: https://www.cnblogs.com/shouke/p/11569464.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。