Hugh's Blog

MySQL 5.7 group by 问题

最近在使用 MySQL 碰到一个问题:

ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.post.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

查了下,是因为 MySQL 5.7 默认开启 only_full_group_by 的原因,可以使用 select @@global.sql_mode; 来进行查看是否有开启。

开启了之后,如果查询语句中有 group by 语句或者涉及到数据分组,则 select columns 中的列都必须在 group by 中使用或者对列增加聚合函数处理,因为在严格模式下,MySQL 并不清楚分组中需要返回哪一行的数据,因此必须指明。

要关闭的话可以修改配置值,如 my.cnf 文件,也可以使用命令 set global sql_mode=''; 等。

另一种做法就是对查询语句进行修改,如去掉不必要的列,或者对列进行聚合函数处理,如 maxcountgroup_concat 等,如:

select max(id) as max_id, group_concat(distinct type) as type, status, count(*) as total from post group by status order by max(created_at) desc;