假设我有一张这样的桌子

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

谢谢!

最佳答案

这一个使用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

关于mysql - SQL如何通过值选择最近的时间戳?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26552976/

10-13 04:43