简体   繁体   中英

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

  • My requirement is to get id based on latest frame (based on date-time) is inserted with group by vehicle id.

在此处输入图片说明

在此处输入图片说明

I have tried with below query

 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
  • The output will not give the proper id.
  • So, I want the id for latest frame inserted with group by vehicle_id.
  • Max(id) or Max(info_datetime) query will not give the accurate result.
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

Your attempt is almost there, but you need to join by id as well:

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

Another way to do it is to filter with a correlated subquery:

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 
)
  • Finally got the solution for above.
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
  • It will take approx 2 to 3 seconds to execute in around 25 lac records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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