mysql查询报错only_full_group_by

为什么一直报错说没分组呢?看了半天也没看出来问题
SQL_ERROR_INFO: "Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'practice_record.submit_time' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by"

select 
date_format(submit_time,'%Y%m') as submit_month,
count(*) as month_q_cnt,
round(count(*)/day(last_day(submit_time)),3) as avg_day_q_cnt 
from practice_record 
group by date_format(submit_time,'%Y%m') 
union all
select  
'2021汇总' as submit_month,
count(*) as month_q_cnt,
round(count(*)/31,3) as avg_day_q_cnt 
from practice_record
order by submit_month;

day(last_day(submit_time)),3)既不是常数量比如值4,也不在group by 列表内,所以报错。

这个错误是因为 MySQL 的 sql_mode 设置为 only_full_group_by,它要求在使用 GROUP BY 语句时,SELECT 中的所有列都必须出现在 GROUP BY 子句中或者使用一个聚合函数对其进行处理,否则将会报错。在你的 SQL 语句中,SELECT 中包含了 submit_time 这个非聚合字段,并且没有出现在 GROUP BY 子句中,因此导致了该错误。
解决该问题的方法有两种:
将 sql_mode 设置为非 only_full_group_by 模式。可以通过修改 MySQL 的配置文件 my.cnf 或者在运行时使用 SET sql_mode = '' 命令来实现。
在 SELECT 中将 submit_time 字段用聚合函数进行处理(例如 MIN()、MAX() 等),或者将该字段也加入到 GROUP BY 子句中。

需要注意的是,虽然关闭 only_full_group_by 可以解决该问题,但是这可能会导致一些不规范的 SQL 语句执行后结果不准确而导致业务问题。因此,最好的方式是在编写 SQL 语句时注意符合 only_full_group_by 的规则,这样既可以保证正确性,也可以避免该错误的发生。