group by问题

在使用group by进行查询结果分组的时候,报错:

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'goodsinfo.item.amount' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

报错原因以及解决方法:

这里的mysql的sql模式采用了全模式匹配,也就是sql_mode=only_full_group_by,出现了依赖冲突。也就是说select后面的字段,除了聚合函数,都必须出现在group by 的后面。因为你是要利用某个字段进行分组,那么该字段就存在于select 后面。除了聚合函数select 后面的字段都应该要出现在group by 后面。

#执行以下sql语句以上错误
SELECT item.amount "订单数量",MONTH(d.order_date) orderDate FROM `order` d INNER JOIN orderitem item ON d.order_id=item.order_id GROUP BY d.order_date; 
#如果要实现按照月分组,统计每个月的订单数量,应该使用这个sql语句
SELECT MONTH(d.order_date) "月份",COUNT(item.amount) "订单数量" FROM `order` d INNER JOIN orderitem item ON d.order_id=item.order_id GROUP BY MONTH(d.order_date) ORDER BY MONTH(d.order_date); 

where,group by后面关于是否能够接聚合函数的问题

  • where 子句后面是不能够连接聚合函数的。聚合函数有sum(),count(),avg(),max(),min()等等其他函数。
  • group by 子句后面连接的是要分组的列,having设置分组条件,这个having子句后面是可以连接聚合函数的。
原文地址:https://www.cnblogs.com/jasonboren/p/11362271.html