Mysql5.7遇到的group by查询问题解决

mysql 5.7  sql_mode模式中。默认启用了ONLY_FULL_GROUP_BY。

ONLY_FULL_GROUP_BY是MySQL提供的一个sql_mode,通过这个sql_mode来提供SQL语句GROUP BY合法性的检查。

this is incompatible with sql_mode=only_full_group_by这句话提示了这违背了mysql的规则,only fully group by,也就是说在执行的时候先分组,根据查询的字段(select的字段)在分组的内容中取出,所以查询的字段全部都应该在group by分组条件内;一种情况例外,查询字段中如果含有聚合函数的字段不用包含在group by中,

后来发现Order by排序条件的字段也必须要在group by内,排序的字段也是从分组的字段中取出。

解决办法:

1.set@@sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

去掉ONLY_FULL_GROUP_BY即可正常执行sql.

2. 不去ONLY_FULL_GROUP_BY, 时 select字段必须都在group by分组条件内(含有函数的字段除外)。(如果遇到order by也出现这个问题,同理,order by字段也都要在group by内)。

3.利用ANY_VALUE()这个函数 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

This function is useful for GROUP BY queries when the ONLY_FULL_GROUP_BY SQL mode is enabled, for cases when MySQL rejects a query that you know is valid for reasons that MySQL cannot determine. The function return value and type are the same as the return value and type of its argument, but the function result is not checked for the ONLY_FULL_GROUP_BY SQL mode.

用上面的第三种方法解决的sql语句可写成:

1

SELECT ANY_VALUE(id)as id,ANY_VALUE(uid) as uid ,ANY_VALUE(username) as username,ANY_VALUE(title) as title,ANY_VALUE(author) as author,ANY_VALUE(thumb) as thumb,ANY_VALUE(description) as description,ANY_VALUE(content) as content,ANY_VALUE(linkurl) as linkurl,ANY_VALUE(url) as url,ANY_VALUE(group_id) as group_id,ANY_VALUE(inputtime) as inputtime, count(id) as count FROM `news` GROUP BY `group_id` ORDER BY ANY_VALUE(inputtime) DESC LIMIT 20

ONLY_FULL_GROUP_BY的语义就是确定select target list中的所有列的值都是明确语义,简单的说来,在此模式下,target list中的值要么是来自于聚合函数(sum、avg、max等)的结果,要么是来自于group by list中的表达式的值

除了修改sql_mode的方式来解决此问题外:

Mysql5.7遇到的group by查询问题解决_第1张图片

Mysql5.7遇到的group by查询问题解决_第2张图片

Mysql5.7遇到的group by查询问题解决_第3张图片

 

你可能感兴趣的:(Mysql)