我是MySQL的新手,我正在试图弄清楚如何计算日志表中各行之间的时间。
该表是一个基本表,包含ID,主机名,信息,时间戳,数据如:
+---+----------+-------------------+---------------------+
|ID | Hostname | Info | Timestamp |
+---+----------+-------------------+---------------------+
|445| switch1 | "port 1 inserted" | 2013-01-19 19:51:40 |
|446| switch1 | "port 2 inserted" | 2013-01-19 19:59:41 |
|447| Router2 | "alarm fan speed" | 2013-01-19 20:00:40 |
|448| switch1 | "alarm fan speed" | 2013-01-19 20:12:20 |
|449| Router2 | "alarm fan speed" | 2013-01-19 21:42:41 |
+---+----------+-------------------+---------------------+
所以基本上我想得到具有相同HOSTNAME的行之间的时差,在这种情况下,在行445和446之间它将导致8分1秒。在446和448之间,它将导致12分39秒。等等...
对此有任何提示将不胜感激。
答案 0 :(得分:1)
这将为您提供行之间的时间差异:
SELECT c.info,
CASE
WHEN f.`timestamp` IS NOT NULL THEN
Timestampdiff(second, f.`timestamp`,
c.`timestamp`)
ELSE NULL
end AS time_diff
FROM (SELECT @rowa := @rowa + 1 AS id,
a.hostname,
a.info,
a.`timestamp`
FROM sparkles a
JOIN (SELECT @rowa := 0) b
WHERE a.hostname = 'switch1') c
LEFT JOIN (SELECT @rowb := @rowb + 1 AS id,
d.hostname,
d.info,
d.`timestamp`
FROM sparkles d
JOIN (SELECT @rowb := 0) e
WHERE d.hostname = 'switch1') f
ON f.id = c.id - 1
结果(对于 switch1 作为hostname
)
| INFO | TIME_DIFF | ------------------------------- | port 1 inserted | (null) | | port 2 inserted | 481 | | alarm fan speed | 759 |
结果(对于 Router2 作为hostname
)
| INFO | TIME_DIFF | ------------------------------- | alarm fan speed | (null) | | alarm fan speed | 6121 |
答案 1 :(得分:0)
试试这个:
SELECT id, IF(@lastdate = '', NULL, TIMESTAMPDIFF(SECOND, TIMESTAMP, @lastdate)),
@lastdate:=TIMESTAMP
FROM tablename, (SELECT @lastdate:='') a;