错误 1055 (42000):SELECT 列表的表达式 #1 不在 GROUP BY 子句中...这与 sql_mode=only_full_group_by 不兼容

ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause ... this is incompatible with sql_mode=only_full_group_by

我正在使用 MYSQL 5.7。我想获取具有不同 device_id 的最近行。我尝试了这些查询:

查询 1

SELECT `table`.`id`, `table`.`device_id` FROM `table` WHERE (id IN (SELECT id FROM (SELECT * FROM table ORDER BY date_modified DESC) AS last_modified GROUP BY device_id) and device_id <> '');

+----+------------------+
| id | device_id        |
+----+------------------+
|  5 | ffcecafe5eed4fba |
|  6 | ffcecafe5eed4fba |
|  8 | 71085f00e527bae0 |
+----+------------------+
3 rows in set (0.00 sec)

但它并没有删除重复项。

子查询 1

SELECT id FROM (SELECT * FROM table ORDER BY date_modified DESC) AS last_modified GROUP BY device_id;
ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'last_modified.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

这给出了错误。然后我在 MySQL 网站上发现使用 ANY_VALUE() 来消除这个错误。

子查询 2

SELECT ANY_VALUE(id) FROM (SELECT * FROM table ORDER BY date_modified DESC) AS last_modified GROUP BY device_id;
+---------------+------------------+
| ANY_VALUE(id) | device_id        |
+---------------+------------------+
|             7 |                  |
|             8 | 71085f00e527bae0 |
|             5 | ffcecafe5eed4fba |
+---------------+------------------+
3 rows in set (0.00 sec)

这给出了不同的 ID。但是当我在上面的查询 1 中使用 ANY_VALUE 时,它给出了相同的结果。

如何在 MySQL 5.7 中查询不同的最近行?


可能重复

MySQL 5.7 return all columns of table based on distinct column

这是对我有用的查询-

SELECT m1.*
FROM messages m1 LEFT JOIN messages m2
 ON (m1.name = m2.name AND m1.id < m2.id)
WHERE m2.id IS NULL;

感谢@Shadow 对 possible duplicate 的 link。