简体   繁体   English

MySQL-查询为每个设备选择最后一行

[英]MySQL - Query that select last row for each devices

I have 2 tables on my DB: 我的数据库中有2个表:

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行。 Location messages may come at ANY order, could be all scrambled or the last 1000 could be from same device. 位置消息可能以任何顺序出现,可能全部被打乱,或者最后1000条可能来自同一设备。

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. INNER JOIN到每个设备的最新位置的子集。 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. 需要为max(code)加上别名,因为列名不是code。

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

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