#1055 – Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 解决方法

今天,项目mysql5.5升级到5.7后,结果我执行“MySQL查询每个商品的平均价格”SQL语句:

SELECT goods_id,goods_name,AVG(store_price) FROM `ns_storegoods_price` WHERE `pic_id` in(41,42) group by `goods_id`;

报错如下:

#1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.ns_storegoods_price.goods_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

中文翻译

#1055-SELECT列表的表达式#2不在GROUP BY子句中,并且包含未聚合的列'test.ns_storegoods_price.goods_name',该列在功能上不依赖于GROUP BY子句中的列; 这与sql_mode = only_full_group_by不兼容

#1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'test.ns_storegoods_price.goods_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

 

原因:

经过各种分析和查阅大量的资料,最终找到原因是:

我原来的数据库版本是5.5,新升级的数据库的版本是5.7以上的。

MySQL5.7以上的默认模式配置是 ONLY_FULL_GROUP_BY

大概意思可就是如果有用到sum、counts......之类的聚合函数,必须要把字段都加入group by里。

 

解决方法

知道了具体的原因,解决起来就容易多了。

 

我只需要顺着这个思路把MySQL语句改成如下即可!

SELECT goods_id,goods_name,AVG(store_price) FROM `ns_storegoods_price` WHERE `pic_id` in(41,42) group by `goods_id`,`goods_name`;

 

注意:

由于我这是要计算每个商品的平均价格,我需要利用 group by 去重,group by这里就不能多个字段了,因此我需要继续改写成如下SQL语句:

SELECT goods_id,AVG(store_price) FROM `ns_storegoods_price` WHERE `pic_id` in(41,42) group by `goods_id`;
    A+
发布日期:2020年09月02日 16:35:45  所属分类:MySQL
最后更新时间:2020-09-02 18:21:21
付杰
  • ¥ 1999.9元
  • 市场价:20000元
  • ¥ 15元
  • 市场价:15元
  • ¥ 79.0元
  • 市场价:99.0元
  • ¥ 69.0元
  • 市场价:99.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: