计算当前行和上一行之间的时间差

时间:2017-08-14 09:29:45

标签: php mysql

我的Web应用程序有以下表格,我想添加另一列来获取当前行和上一行之间的时差。我怎样才能实现它?

目前这是来自php Application的SQL调用

$stmt = $db->prepare("SELECT device,lat,lon, speed, mode, DATE (`currentTime`) ,TIME_FORMAT(`currentTime`, '%H:%i:%s')
                            FROM myTable 
                            WHERE  device=?  limit ?");
$stmt ->bind_param('ii', $device_Number ,$limit);
$stmt ->bind_result($device, $lat, $lon, $speed, $mode, $currentDate, $currentTime);
$stmt ->execute();

enter image description here

2 个答案:

答案 0 :(得分:1)

这里我给出了具有日期时间差异的样本数据,在这里您将数据保存在2个不同的列中 所以将日期差异作为2列' timedifference'和' daydifference'

testtime

    id  date1       time1 
    1   2017-08-14  01:06:11
    2   2017-08-14  01:09:13
    3   2017-08-14  01:16:10
    4   2017-08-14  01:21:00
    5   2017-08-15  01:21:00
    6   2017-08-15  02:13:00

Mysql查询

    SELECT A.id, A.time1, TIMESTAMPDIFF(SECOND,A.time1,B.time1) AS timedifference,
    TIMESTAMPDIFF(DAY,A.date1,B.date1) AS daydifference 
    FROM testtime A INNER JOIN testtime B ON B.id = (A.id + 1) 
    ORDER BY A.id ASC 

答案 1 :(得分:1)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(device INT NOT NULL 
,lat DECIMAL(10,6) NOT NULL
,lon DECIMAL(10,6) NOT NULL
,speed DECIMAL(5,2)
,mode INT NOT NULL
,dt DATETIME NOT NULL
,PRIMARY KEY(device,dt)
);

INSERT INTO my_table VALUES
(117,1.415738,103.82360,28.8,3,'2017-07-12 22:07:40'),
(117,1.424894,103.82561,31.9,3,'2017-07-12 22:08:41'),
(117,1.429965,103.82674,10.9,3,'2017-07-12 22:09:47'),
(117,1.430308,103.82873, 5.2,3,'2017-07-12 22:10:47'),
(117,1.430542,103.83278,13.9,3,'2017-07-12 22:11:48'),
(117,1.430537,103.83325, 3.2,3,'2017-07-12 22:12:47');

SELECT x.*
     , SEC_TO_TIME(TIME_TO_SEC(x.dt)-TIME_TO_SEC(MAX(y.dt))) diff 
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.device = x.device 
   AND y.dt < x.dt 
 GROUP 
    BY x.device
     , x.dt;
+--------+----------+------------+-------+------+---------------------+----------+
| device | lat      | lon        | speed | mode | dt                  | diff     |
+--------+----------+------------+-------+------+---------------------+----------+
|    117 | 1.415738 | 103.823600 | 28.80 |    3 | 2017-07-12 22:07:40 | NULL     |
|    117 | 1.424894 | 103.825610 | 31.90 |    3 | 2017-07-12 22:08:41 | 00:01:01 |
|    117 | 1.429965 | 103.826740 | 10.90 |    3 | 2017-07-12 22:09:47 | 00:01:06 |
|    117 | 1.430308 | 103.828730 |  5.20 |    3 | 2017-07-12 22:10:47 | 00:01:00 |
|    117 | 1.430542 | 103.832780 | 13.90 |    3 | 2017-07-12 22:11:48 | 00:01:01 |
|    117 | 1.430537 | 103.833250 |  3.20 |    3 | 2017-07-12 22:12:47 | 00:00:59 |
+--------+----------+------------+-------+------+---------------------+----------+
6 rows in set (0.00 sec)