If you’re running MySQL 5.7.5 or higher, you might’ve seen this error while trying different types of queries involving GROUP BY, HAVING, and DISTINCT.
Error Code: 1055. Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
The reason is because ONLY_FULL_GROUP_BY is enabled by default. And for good reason.
ONLY_FULL_GROUP_BYis disabled, a MySQL extension to the standard SQL use of
GROUP BYpermits the select list,
ORDER BYlist to refer to nonaggregated columns even if the columns are not functionally dependent on
GROUP BYcolumns. This causes MySQL to accept the preceding query. In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic, which is probably not what you want. Furthermore, the selection of values from each group cannot be influenced by adding an
ORDER BYclause. Result set sorting occurs after values have been chosen, and
ORDER BYdoes not affect which value within each group the server chooses. Disabling
ONLY_FULL_GROUP_BYis useful primarily when you know that, due to some property of the data, all values in each nonaggregated column not named in the
GROUP BYare the same for each group.
The solution is to use MySQL 8’s new window functions. You would be able to grab the latest records based on a group with the following:
WITH list AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY [column name] ORDER BY timestamp DESC) AS latest FROM [table “” not found /]
) SELECT * from list where latest = 1;
And that’s it!