MySQL 排错-解决MySQL非聚合列未包含在GROUP BY子句报错问题
排错-解决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
[其它节点配置]
...