发现问题
最近在将mysql升级到mysql 5.7后,进行一些group by 查询时,比如下面的
SELECT *, count(id) as count FROM `news` GROUP BY `group_id` ORDER BY `inputtime` DESC LIMIT 20
就会报如下错误:
SELECT list is not in GROUP BY clause and contains nonaggregated column ‘news.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。
ONLY_FULL_GROUP_BY是MySQL提供的一个sql_mode,通过这个sql_mode来提供SQL语句GROUP BY合法性的检查。
http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_only_full_group_by
this is incompatible with sql_mode=only_full_group_by这句话提示了这违背了mysql的规则,only fully group by,也就是说在执行的时候先分组,根据查询的字段(select的字段)在分组的内容中取出,所以查询的字段全部都应该在group by分组条件内;一种情况例外,查询字段中如果含有聚合函数的字段不用包含在group by中,就像我上面的count