简体   繁体   中英

MySQL Query - Retrieve all devices info with latest timestamp value

I have following two tables:

devices :

在此处输入图片说明

tracking :

在此处输入图片说明

I need to construct a MySQL query which will return all devices with latest latitude and longitude. The latest rows can be picked by fetching only tracking rows for each device which have latest timestamp value. I can't able to construct this query by myself. Please help.

devices.Name, devices.IMEI, tracking.latitude, tracking.longitude devices.name,devices.IMEI,tracking.latitude,tracking.longitude

thanks

to get top data from tracking

select *
from   tracking join (select imei, max(ctimestamp) as maxtime
                      from tracking
                      group by imei) as sub
       on sub.imei = tracking.imei
          and sub.ctimestamp = tracking.timestamp

you can surely join the devices table and print the name yourself

This should do it, use a left join to make sure there are no newer rows;

SELECT d.name, d.IMEI, t.latitude, t.longitude
FROM devices d
JOIN tracking t 
    ON d.IMEI=t.IMEI
LEFT JOIN tracking t2
     ON d.IMEI=t2.IMEI
    AND t2.ctimestamp>t.ctimestamp
WHERE t2.IMEI IS NULL

SQLfiddle for testing .

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