mysql报错Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column问题
今天sql一对多关联查询发现一个错误,提示说查询的字段不在group by的子句中,因为sql_mode是only_full_group_by。
报错信息:
#1055 - Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'xt_sc.t_comment.content' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
执行的sql语句
SELECT n.id, n.title, n.qq, u.username, c.content, c.create_time FROM `t_need` AS `n` LEFT JOIN `t_users` `u` ON `n`.`user_id`=`u`.`id` INNER JOIN ( SELECT max(id) as id,n_id,content,create_time FROM `t_comment` GROUP BY `n_id` ) AS `c` ON `n`.`id`=`c`.`n_id` WHERE `n`.`status` = 2 AND `n`.`form` = 1 GROUP BY `n`.`id` ORDER BY `stick` DESC,`n`.`update_time` DESC LIMIT 0,30
问题出现的原因:
MySQL 5.7.5及以上功能依赖检测功能。如果启用了ONLY_FULL_GROUP_BY SQL模式(默认情况下),MySQL将拒绝选择列表,HAVING条件或ORDER BY列表的查询引用在GROUP BY子句中既未命名的非集合列,也不在功能上依赖于它们。(5.7.5之前,MySQL没有检测到功能依赖关系,默认情况下不启用ONLY_FULL_GROUP_BY。有关5.7.5之前的行为的说明,请参见“MySQL 5.6参考手册”。)
查看mysql本地的sql_mode命令:
select @@sql_mode; show variables like 'sql_mode';
输出sql_mode的值:ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZER
_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
确实第一个是only_full_group_by,这个模式说明对于GROUP BY聚合操作,如果在SELECT中的列,没有在GROUP BY中出现,那么将认为这个SQL是不合法的,因为列不在GROUP BY从句中。就是说不允许select的列没有出现在group by的子句中。
在5.7.5以上,sql的默认模式配置是ONLY_FULL_GROUP_BY。
解决办法1:
简单粗暴的解决方法是删除ONLY_FULL_GROUP_BY,不推荐
在数据库控制台输入命令:SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
然后再执行查询语句,可以正常查询出结果
解决办法2:
优化sql语句
SELECT n.id, n.title, n.qq, u.username, c.content, c.create_time FROM `t_need` AS `n` LEFT JOIN `t_users` `u` ON `n`.`user_id`=`u`.`id` INNER JOIN ( SELECT a.id,a.n_id,a.content,a.create_time FROM `t_comment` AS `a` LEFT JOIN( SELECT max(id) as id,n_id FROM `t_comment` GROUP BY `n_id` ) AS `b` ON `b`.`n_id`=`a`.`n_id` WHERE `a`.`id` = `b`.`id` ) AS `c` ON `n`.`id` = `c`.`n_id` WHERE `n`.`status` = 2 AND `n`.`form` = 1 GROUP BY `n`.`id` ORDER BY `stick` DESC,`n`.`update_time` DESC LIMIT 0,30
执行以上查询语句,可以正常查询出结果。
done!
如果觉得这文章还算用心,请劳驾点击右下角的推荐,这是对我们这些做开源分享的最大的肯定,谢谢。
作者:zqifa
出处:https://www.cnblogs.com/zqifa/
欢迎访问新博客地址:https://www.l1mn.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。