我正在使用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)
但它并没有删除重复项。
SubQuery 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()来删除此错误。
SubQuery 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
答案 0 :(得分:1)
这是对我有用的查询 -
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的链接。