简体   繁体   中英

MySQL - Query that select last row for each devices

I have 2 tables on my DB:

CREATE TABLE IF NOT EXISTS `location` (
  `code` int(11) NOT NULL AUTO_INCREMENT,
  `IMEI` varchar(15) NOT NULL,
  `latitude` decimal(10,6) NOT NULL,
  `longitude` decimal(10,6) NOT NULL,
  `speed` tinyint(3) unsigned NOT NULL,
  `course` smallint(6) NOT NULL,
  `satellites` tinyint(3) unsigned NOT NULL,
  `datetime` datetime NOT NULL,
  `rt_dif` tinyint(1) NOT NULL,
  `pos_notpos` tinyint(1) NOT NULL,
  `MCC` smallint(5) unsigned NOT NULL,
  `MNC` smallint(5) unsigned NOT NULL,
  `LAC` smallint(5) unsigned NOT NULL,
  `CELL_ID` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2323 ;

CREATE TABLE IF NOT EXISTS `devices` (
  `code` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `IMEI` varchar(15) NOT NULL,
  `client` int(11) NOT NULL,
  `model` varchar(50) NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

I have devices which belong to different clients and I want to select the last location row of each device of a given client. Location messages may come at ANY order, could be all scrambled or the last 1000 could be from same device.

Can anyone help me?

This is one way... though there is faster using coorlative subquery.

SELECT D.*, L.*
FROM Devices D
LEFT JOIN Location L
 on D.IMEI = L.IMEI
INNER JOIN (Select max(Code) mCode, IMEI From Location group by IMEI) X  
 on D.IMEI = X.IMEI  
and D.Code = X.mCode

Intent:

  • Return all devices and their most recent location if one exists.
  • OUTER JOIN devices to location so we get all devices
  • INNER JOIN to a subset of most recent locations for each device. This join effectively eliminates historical locations.

My understanding is you want the "Last" as determined by the Code field in location, record for each device. Simply put you want to know the last reported location of each device in the system; none of the history.

To get this, I assume you only care about location records for devices in the device table. Thus the reason we start with the devices as we want them all regardless if a last location has been reported or not.

Needed to alias the max(code) as the column name wouldn't be code.

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