SQL如何按值选择最新的时间戳?

时间:2014-10-24 17:16:25

标签: mysql sql group-by timestamp

假设我有一张这样的表

CREATE TABLE events (
  id INT,
  sensor INT,
  event_type INT,
  time datetime
  );

INSERT INTO events VALUES (0,2,4,'2012-06-08 12:13:14');
INSERT INTO events VALUES (1,3,4,'2012-06-08 13:13:14');
INSERT INTO events VALUES (2,2,4,'2012-06-08 12:15:14');
INSERT INTO events VALUES (3,1,6,'2012-06-08 15:13:14');

检索传感器添加的最新事件的“最佳”方法是什么?所以结果会像这样(请注意,id 2显示而不是id 0,因为id 2是最近的:

ID   sensor
3      1
1      3
2      2

我写了一个像这样的选择,但还有其他方法吗?或者更简单的方式来归档这个?

SELECT id,time,sensor,event_type 
FROM events s1
WHERE time = (
  SELECT MAX(time) FROM events s2 WHERE s1.sensor = s2.sensor
)
ORDER BY time DESC

谢谢!

3 个答案:

答案 0 :(得分:3)

这一个使用GROUP BY的变体,需要与您的数据一起运行并查看性能

SELECT events.id, events.sensor 
FROM events
JOIN
(
    SELECT sensor, max(time) as maxTime
    FROM events
    group by sensor
) T
on events.sensor = T.sensor
and events.time = T.maxTime
ORDER BY events.time DESC

答案 1 :(得分:3)

select * from events 
     where time in(SELECT max(time) FROM events 
            group by sensor_id,event_type) 
     Order by time desc;

答案 2 :(得分:0)

这无需使用聚合函数即可工作:

select e1.* from events e1 
  left outer join events e2 on e1.sensor = e2.sensor 
    and e1.id != e2.id 
    and e1.time < e2.time 
  where e2.time is null;