【问题标题】:How to find the timestamp in a table that closest with a timestamp in another table(MySQL)如何在一个表中找到与另一个表中的时间戳最接近的时间戳(MySQL)
【发布时间】:2014-10-13 16:44:43
【问题描述】:

我有两张表 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';

不幸的是,我发现Fuel中没有任何时间戳与DrivingTime中的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

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

【问题讨论】:

  • 你需要通过 timestampdiff 函数在两者之间使用连接

标签: java mysql datetime


【解决方案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 表中行的开始时间和停止时间之间的所有行。它将显示开始和停止时间。我添加了一个一分钟的模糊因子来覆盖时间戳中可能存在的轻微错误。

要找到与Fuel 中的每一行最接近的开始时间的DrivingTime 行,您首先需要将该结果集总结如下:

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 中的每一行找到DrivingTime 中的第一个(及时)startTime。

编辑。如果您想要最接近停止时间的时间戳,您可以轻松地将其添加到 SELECT 子句中,如下所示:

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

【讨论】:

  • 我只希望得到两个等于(或最接近)startTime 和 stopTime 的时间戳,因为 startTime 可能在早上 6 点,而 stopTime 可能在上午 10 点,而 Fuel 中的时间戳每两分钟返回一次。所以从表中的这么多时间戳中,我必须选择 6.am 和 10.am 的时间戳
  • 如果我有一系列 startTime 和 stopTime 记录,例如:(6.am-10.am)(1.pm-3p.pm),(5.pm-下午 6 点)等?而且我必须将时间戳与上面的每一时间相匹配。我试过你的建议,但没有结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多