如果我有一个包含两列的表,名称和时间戳,以及一堆将具有共享名称的行。如何选择共享同一名称的每组行的最新行?
谢谢!
答案 0 :(得分:2)
SELECT name, MAX(timestamp) FROM Table1 GROUP BY name
编辑:根据评论,请尝试以下方法:
SELECT name, timestamp, col3, col4
FROM Table1 t1
WHERE timestamp = (SELECT MAX(t2.timestamp)
FROM Table1 t2
WHERE t1.name = t2.name);
由Mchl
添加没有依赖子查询的版本(应该表现更好)
SELECT
t1.name, t1.timestamp, t1.col3, t1.col4
FROM
Table1 AS t1
CROSS JOIN (
SELECT
name, MAX(timestamp) AS timestamp
FROM
Table1
GROUP BY
name
) AS sq
USING (name,timestamp)
答案 1 :(得分:1)
然后你需要一个子查询:
SELECT columns
FROM Table1 t1
WHERE row_id = (SELECT row_id
FROM table1 t2
WHERE t1.name = t2.name
ORDER BY timestamp DESC
LIMIT 1)
GROUP BY name
已编辑,已忘记按名称分组