在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
发现问题 最近在将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
后来发现Order by排序条件的字段也必须要在group by内,排序的字段也是从分组的字段中取出。 不明白的可以去看一下。 解决办法: 1. 去掉ONLY_FULL_GROUP_BY即可正常执行sql. 2. 不去ONLY_FULL_GROUP_BY, 时 select字段必须都在group by分组条件内(含有函数的字段除外)。(如果遇到order by也出现这个问题,同理,order by字段也都要在group by内)。 3.利用 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语句可写成 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 我选用的是第3种方法。 总结 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对极客世界的支持。 |
请发表评论