这个问题在这里已有答案:
ID | serial | created_at | data 1..45
1 | 001 | timestamp | ....
2 | 002 | timestamp | ....
3 | 003 | timestamp | ....
4 | 001 | timestamp | ....
5 | 002 | timestamp | ....
6 | 001 | timestamp | ....
7 | 003 | timestamp | ....
8 | 004 | timestamp | ....
9 | 001 | timestamp | ....
我期待ID 9,8,7,5的结果,因为我需要每个序列的最新行
=> "SELECT * FROM `rig_stats` GROUP BY `rig_stats`.`serial` ORDER BY `rig_stats`.`id` DESC"
然而,这给了我第一次出现,通过id命令desc所以结果是1 2 3 8
并且不是我想要的。
使用mysql Ver 14.14 Distrib 5.7.21, for Linux (x86_64)
您可以加入子查询,查找每个序列的最新行:
SELECT s1.*
FROM serial s1
INNER JOIN
(
SELECT serial, MAX(created_at) AS max_created_at
FROM serial
GROUP BY serial
) s2
ON s1.serial = s2.serial AND
s1.created_at = s2.max_created_at;