[英]Why isn't the GROUP BY clause in this MySQL statement throwing errors?
I am using w3s as my example in here 我在这里使用w3s作为我的例子
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders,
Orders.OrderDate
FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;
I am confused why the above statement isn't throwing an error. 我很困惑为什么上面的陈述没有抛出错误。 How does MySQL know which
OrderDate
to use when we are aggregating by all OrderID
? 当我们通过所有
OrderID
进行聚合时,MySQL如何知道要使用哪个OrderDate
?
How does mysql know which OrderDate to use when we are aggregating by all OrderID?
当我们通过所有OrderID进行聚合时,mysql如何知道要使用哪个OrderDate?
It doesn't. 它没有。 It just picks one, because it assumes you would have grouped by all the necessary columns, and any columns that weren't in the
GROUP BY
and weren't subject to any aggregate functions would have the same values for each group. 它只选择一个,因为它假定您将按所有必需的列进行分组,并且任何不在
GROUP BY
且不受任何聚合函数约束的列将为每个组具有相同的值。
It's non-standard behavior that works as an optimization, allowing the server to "leak" one of the values through from each group in the source rows into the result-set, reducing the size of the data the GROUP BY
has to manage. 这是非标准行为,可用作优化,允许服务器将源行中每个组的一个值“泄漏”到结果集中,从而减少
GROUP BY
必须管理的数据大小。 Which source row's value is used for each group is undefined, so this is intended to be used only in queries where the non-grouped columns are functionally dependent on the grouped columns... because, in that case, "which" row doesn't matter, because they're all the same within each group. 每个组使用哪个源行的值是未定义的,因此这仅用于非分组列在功能上依赖于分组列的查询...因为,在这种情况下,“哪个”行不会无所谓,因为他们在每个小组中都是一样的。
MySQL extends the standard SQL use of
GROUP BY
so that the select list can refer to nonaggregated columns not named in theGROUP BY
clause.MySQL扩展了
GROUP BY
的标准SQL使用,因此选择列表可以引用GROUP BY
子句中未命名的非聚合列。 This means that the [queries excluding non-aggregated columns are] legal in MySQL.这意味着[不包括非聚合列的查询]在MySQL中是合法的。 You can use this feature to get better performance by avoiding unnecessary column sorting and grouping.
您可以通过避免不必要的列排序和分组来使用此功能来获得更好的性能。 However, this is useful primarily when all values in each nonaggregated column not named in the
GROUP BY
are the same for each group.但是,当
GROUP BY
中未命名的每个非聚合列中的所有值对于每个组都相同时,这非常有用。 The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.服务器可以自由选择每个组中的任何值,因此除非它们相同,否则所选的值是不确定的。 Furthermore, the selection of values from each group cannot be influenced by adding an
ORDER BY
clause.此外,添加
ORDER BY
子句不会影响每个组中值的选择。 [emphasis added][强调补充]
https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html
https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html
You can disable this behavior by including ONLY_FULL_GROUP_BY
in @@SQL_MODE . 您可以通过在@@ SQL_MODE中包含
ONLY_FULL_GROUP_BY
来禁用此行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.