You should be using WHERE
, not HAVING
if you're trying to filter records. HAVING
is used to apply the filter after grouping and sorting have happened.
Regardless, the issue lies with how MySQL uses GROUP BY
. GROUP BY
should be used with an aggregate; MySQL extends the functionality for convenience. You're receiving different results because of the way it sorts and groups the columns.
MySQL extends the use of
GROUP BY
so that the select list can refer to nonaggregated columns not named in theGROUP BY
clause. This means that the preceding query is 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.