In short, I'm trying to order a dateset by date, and then group by another column, thus selecting the latest row of each.
Query:
SELECT name, datetime
FROM (
SELECT *
FROM `requests`
ORDER BY datetime
) a
GROUP BY a.name;
Error:
#1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'a.datetime' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Example table:
CREATE TABLE `requests` (
`id` int(8) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
`datetime` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
The goal is to prevent this error from happening without having to change the default sql-mode.
After reading more about group by
and only_full_group_by
, I currently do not understand why the sub-query is affecting the outer query.
Query is written in accordance to https://stackoverflow.com/a/16307932/3852461