繁体   English   中英

获取带有最新日期时间而不是 id 的每个组的带有 id 的最新记录 - mysql

[英]Get latest records with id for each group with latest date-time not id - mysql

  • 我的要求是根据最新帧(基于日期时间)获取 id,并按车辆 id 插入组。

在此处输入图片说明

在此处输入图片说明

我试过下面的查询

 select a.id,a.vehicle_id,a.info_datetime 
  from table_name a 
  join (select id, max(info_datetime) as maxdt from table_name group by vehicle_id) as b 
    on a.info_datetime = b.maxdt
  • 输出不会给出正确的 id。
  • 所以,我想要最新帧的 id 插入到 group by Vehicle_id 中。
  • Max(id) 或 Max(info_datetime) 查询不会给出准确的结果。
SELECT id, vehicle_id FROM table_name as a WHERE info_datetime = 
(SELECT MAX(info_datetime) FROM table_name as b WHERE a.vehicle_id = b.vehicle_id)
GROUP BY vehicle_id

您的尝试几乎就在那里,但您还需要通过id加入:

select a.id,a.vehicle_id,a.info_datetime 
from table_name a 
join (
    select vehicle_id, max(info_datetime) as maxdt from table_name group by vehicle_id
) as b on a.info_datetime = b.maxdt and a.vehicle_id = b.vehicle_id

另一种方法是使用相关子查询进行过滤:

select a.*
from table_name a
where a.info_datetime = (
    select max(b.info_datetime) from table_name b where b.vehicle_id = a.vehicle_id 
)
  • 终于得到了上面的解决方案。
SELECT id, vehicle_id, info_datetime
FROM table_name
WHERE id in (
    select max(m2.id) from table_name m2 group by m2.vehicle_id)
ORDER BY vehicle_id asc,info_datetime DESC
  • 在大约 25 个 lac 记录中执行大约需要 2 到 3 秒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM