选择指定日期之前的最后一个事件

时间:2016-02-16 10:42:45

标签: mysql

假设我有2个表格如下所示: EventData几乎每60秒就会为每个设备包含gps事件(表示大量数据)

CREATE TABLE IF NOT EXISTS `EventData` (
  `accountID` varchar(32) NOT NULL,
  `deviceID` varchar(32) NOT NULL,
  `timestamp` int(10) unsigned NOT NULL,
  `statusCode` int(10) unsigned NOT NULL,
  `latitude` double DEFAULT NULL,
  `longitude` double DEFAULT NULL,
  `gpsAge` int(10) unsigned DEFAULT NULL,
  `speedKPH` double DEFAULT NULL);

Device包含设备信息,

CREATE TABLE IF NOT EXISTS `Device` (
  `deviceID` varchar(32) NOT NULL,
  `groupID` varchar(32) DEFAULT NULL,
  `equipmentType` varchar(40) DEFAULT NULL,
  `speedLimitKPH` double DEFAULT NULL,
  `deviceType` varchar(24) DEFAULT NULL,
  `pushpinID` varchar(32) DEFAULT NULL,
  `description` varchar(50) DEFAULT NULL);

我想要一个查询,在给定的时间戳(timestamp<$givenTimestamp)之前返回每个设备的最后一个事件,并且它必须是单个查询,否则将耗费大量时间。有没有办法解决这个问题?

我试过了:

SELECT
    d.deviceID,
    d.description,
    d.pushpinID,
    e.latitude,
    e.longitude,
    MAX(e.timestamp) as timestamp
FROM
    Device as d
INNER JOIN
    EventData as e
        ON d.deviceID = e.deviceID
WHERE
    timestamp <= $time
GROUP BY
    (e.deviceID);

但它不会归还我想要的东西。它返回最后一个事件,而不是给定时间之前的最后一个事件。

1 个答案:

答案 0 :(得分:0)

尝试此查询:

select d.deviceID ,d.description,d.pushpinID,e.latitude,e.longitude, 
       (select max(timestamp) from EventData where deviceID=e.deviceID) as timestamp
FROM Device as d INNER JOIN EventData as e ON d.deviceID=e.deviceID WHERE 
  timestamp < '$time' GROUP BY e.deviceID