mysql - 如何从最近的记录中选择值?

标签 mysql sql sqlite

我有 table

create table events (
  sensor_id integer not null,
  event_type integer not null,
  value integer not null,
  time timestamp unique not null);

insert into events
values
(2,2,5,"2014-02-13 12:42:00"),
(2,4,-42,"2014-02-13 13:19:57"),
(2,2,2,"2014-02-13 14:48:30"),
(3,2,7,"2014-02-13 12:54:39"),
(2,3,54,"2014-02-13 13:32:36");

我只希望每个 sensor_id 和 event_type 的最新值在时间方面

预期结果
sensor_id, event_type   value
2          2            2
2          3            54
2          4            -42
3          2            7

我试过查询
SELECT sensor_id,event_type,value, time
from events
group by sensor_id,event_type
having time = max(time)

为什么它不成功(结果表不包含 sensor_id = 2 和 event_type = 2)

我如何同时使用 mysql 和 sqllite 来解决这个问题,这方面有区别吗?

最佳答案

使用聚合来获取最大时间,然后使用连接来获取与该时间匹配的其余记录:

SELECT e.sensor_id, e.event_type, e.value, e.time
from events e join
     (select sensor_id, event_type, max(time) as maxt
      from events e
      group by sensor_id, event_type
     ) ee
     on e.sensor_id = ee.sensor_id and e.event_type = ee.event_type;

关于mysql - 如何从最近的记录中选择值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29474458/

相关文章:

java - 程序拒绝从 MySQL 数据库获取字符串

php - str_replace 仅使用整个单词

Mysql - where 子句中的左连接问题

sql - 根据列中的重复项选择行

java - SQLite 用户名与 EditText 值进行检查

Python 3.7.4 不使用 SQLITE 3.29.0

sql - MySQL 结果以逗号分隔列表形式

mysql - Rails 应用程序中 mysql 查询性能缓慢

MySQL 一对多主选

sql - 我可以在SQLite表列名中使用问号吗?