I am using w3s as my example in here
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
?
How does mysql know which OrderDate to use when we are aggregating by all OrderID?
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.
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. 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. This means that the [queries excluding non-aggregated columns are] legal in 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 theGROUP BY
are the same for each group. 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 anORDER BY
clause. [emphasis added]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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.