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.
If
ONLY_FULL_GROUP_BYis disabled, a MySQL extension to the standard SQL use ofGROUP BYpermits the select list,HAVINGcondition, orORDER BYlist to refer to nonaggregated columns even if the columns are not functionally dependent onGROUP 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 anORDER BYclause. Result set sorting occurs after values have been chosen, andORDER BYdoes not affect which value within each group the server chooses. DisablingONLY_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 theGROUP BYare the same for each group.– MySQL
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!
Recent Comments