日期:2014-05-16  浏览次数:20638 次

mysql的group by
直接上sql
select id,name,sum(score),sum(money) from table_A
假如说有3条数据
id name score money
1 one 3 10
2 two 5 20
3 thire 7 30
上面的语句不报错?为什么?
按照道理来说应该加入group by 才对的。
求大神们的解释



------解决方案--------------------
简单地说,不是标准的SQL语句
mysql help:
MySQL extends the use of GROUP BY so that you can use non-aggregated columns or calculations in the SELECT list that do not appear in the GROUP BY clause. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. For example, you do not need to group on customer.name in the following query: 
SELECT order.custid, customer.name, MAX(payments)
FROM order,customer
WHERE order.custid = customer.custid
GROUP BY order.custid;

In standard SQL, you would have to add customer.name to the GROUP BY clause. In MySQL, the name is redundant. 



MySQL的扩展,使您可以使用非聚合SELECT列表中的计算列或不出现在GROUP BY子句。您可以使用此功能得到更好的性能,避免不必要的列进行排序和分组。例如,您不需要customer.name组在下面的查询:
------解决方案--------------------
引用 MySQL对GROUP BY的使用进行了扩展,允许选择在GROUP BY子句中没有被提到的字段。如果您没有得到预期的结果,请阅读GROUP BY的说明,请参见12.10节,“与GROUP BY子句同时使用的函数和修改程序”。