1

我是 MySQL 新手,我试图弄清楚如何计算日志表中行之间传递的时间。

该表是具有 ID 、 Hostname 、 Info 、 Timestamp 的基本表,其数据如下:

+---+----------+-------------------+---------------------+
|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 |
+---+----------+-------------------+---------------------+

所以基本上我想获得具有相同主机名的行之间的时间差,在这种情况下,在第 445 行和第 446 行之间,它将导致 8 分 1 秒。并且在 446 和 448 之间会产生 12 分 39 秒。等等...

对此的任何提示将不胜感激。

4

2 回答 2

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

| 信息 | TIME_DIFF |
-------------------------------------------
| 插入端口 1 | (空) |
| 端口 2 已插入 | 481 |
| 风扇转速报警| 第759章

查看演示

结果(对于Router2作为hostname

| 信息 | TIME_DIFF |
-------------------------------------------
| 风扇转速报警| (空) |
| 风扇转速报警| 6121 |

查看演示

于 2013-01-19T19:12:28.543 回答
0

试试这个:

SELECT id, IF(@lastdate = '', NULL, TIMESTAMPDIFF(SECOND, TIMESTAMP, @lastdate)), 
       @lastdate:=TIMESTAMP 
FROM tablename, (SELECT @lastdate:='') a;
于 2013-01-19T19:23:15.710 回答