MySQL sql_mode=only_full_group_by 错误

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'blog.categories.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 模式的,但开启这个模式后,原先的 group by 语句就报错。

原因:

其中 ONLY_FULL_GROUP_BY 就是造成这个错误的原因,

对于 group by 聚合操作,如果在 select 中的列没有在 group by 中出现,那么这个 SQL 是不合法的,因为列不在 group by 从句中,所以设置了 sql_mode=only_full_group_by 的数据库,在使用 group by 时就会报错。