如何在表中找到与另一个表中的时间戳最接近的时间戳(MySQL)

时间:2014-10-13 16:44:43

标签: java mysql datetime

我有两张桌子Fuel和DrivingTime。 Fuel有accountID,deviceID,timestamp,fuelLevel,address。 DrivingTime有startTime,stopTime。我的目标是在时间戳与startTime或stopTime匹配时显示Fuel中的所有字段。我写了这样的查询:

SELECT F.deviceID, F.timestamp, F.fuelLevel,F.address
FROM Fuel F, DrivingTime DT
where (F.timestamp = DT.stopTime or F.timestamp = DT.startTime)
and F.accountID = 'something1' and F.deviceID = 'something2';

不幸的是,我发现在FuelTime中没有任何时间戳与startTime匹配,只有F.timestamp = DT.stopTime返回true。搜索谷歌后,我可以分别将时间戳与startTime和stopTime匹配,但我很困惑将它们匹配在一起。这是代码:

select from_unixtime(F.timestamp), F.fuelLevel, F.address
from gtse.tblFuel F, gtse.tblDrivingTime DT
where DT.stopTime = F.timestamp and F.accountID = 'vinhnghia'
and F.deviceID = '14C-00027'

在这里:

select from_unixtime(F.timestamp), F.fuelLevel, F.address
from gtse.tblFuel F, gtse.tblDrivingTime D
where D.accountID = 'vinhnghia' and D.deviceID = '14C-00027'
and F.timestamp between D.startTime and D.startTime + '60'
order by
abs(F.timestamp - D.startTime) asc limit 1

。那么如何才能在一个查询中匹配上述两个代码呢?

1 个答案:

答案 0 :(得分:1)

这个怎么样:

SELECT DT.startTime, DT.stopTime, F.deviceID, F.timestamp, F.fuelLevel, F.address
  FROM Fuel F
  JOIN DrivingTime ON F.timestamp <= DT.stopTime + INTERVAL 1 MINUTE
                  AND F.timestamp >= DT.startTme - INTERVAL 1 MINUTE
 WHERE /* whatever criteria */

这将找到Fuel表的所有行,这些行位于DrivingTime表中行的开始和停止时间之间。它将显示开始和停止时间。我添加了一分钟的模糊因子来弥补时间戳中可能存在的轻微不准确性。

要找到DrivingTime中与Fuel中每行最接近的开始时间的SELECT MIN(DT.startTime) AS firstFuelTime, F.deviceID, F.timestamp, F.fuelLevel, F.address FROM Fuel F JOIN DrivingTime ON F.timestamp <= DT.stopTime + INTERVAL 1 MINUTE AND F.timestamp >= DT.startTme - INTERVAL 1 MINUTE WHERE /* whatever criteria */ GROUP BY F.deviceID, F.timestamp, F.fuelLevel, F.address 行,您首先需要按如下方式汇总该结果集:

Fuel

这将在SELECT MIN(DT.startTime) AS firstFuelTime, MAX(DT.stopTime) AS lastFuelTime, F.deviceID, F.timestamp, F.fuelLevel, F.address FROM Fuel F JOIN DrivingTime ON F.timestamp <= DT.stopTime + INTERVAL 1 MINUTE AND F.timestamp >= DT.startTme - INTERVAL 1 MINUTE WHERE /* whatever criteria */ GROUP BY F.deviceID, F.timestamp, F.fuelLevel, F.address 中的每一行的DrivingTime中找到第一个(及时)startTime。

修改即可。如果您希望时间戳最接近停止时间,则可以轻松地将其添加到SELECT子句中,如下所示:

{{1}}