2013-03-25 73 views
0

我在商店中有500个自助服务终端,并且有一个表按商店ID跟踪每个打印的时间戳。我需要生成一个记录集,在几秒钟内为我提供打印之间的时间。所有这些数据都存储在一个表中。为每个打印插入一条记录并包含商店ID和时间戳。mySql TimeDiff单行表中的行之间的时间戳

TABLE NAME =打印
ID     STORE_ID    时间戳
                      2013年3月1日00:00:01
                      2013年3月1日00:00:01 *
                      2013年3月1日00:00:01
                      2013年3月1日0时00分12秒*
                      2013年3月1日0点00分06秒
                      2013年3月1日00:00:15 *

我需要拉长时间,以秒储存所有#2打印之间。 *是这样您可以轻松找到需要比较的记录。

记录集结果下面:

  ID   STORE_ID     myTimeDiffSeconds
                                                           

这需要是简单,快速。我可以不用临时表吗?

+0

这里有几个答案:http://stackoverflow.com/questions/5402938/mysql-find-difference-between-rows-of-the-sametable – ethrbunny 2013-03-25 17:00:17

回答

1

可以使用会话变量

第一个使用相关查询
2.写在两个方面
1.查询正是ethrbunny指出

mysql> SELECT t1.id, 
      t1.store_id, 
      timestampdiff(second,IFNULL((SELECT MAX(t2.timestamp) 
              FROM print t2 
             WHERE t2.store_id=2 
               AND t2.timestamp< t1.timestamp) 
         ,t1.timestamp),t1.timestamp) myTimeDiffSeconds 
    FROM print t1 
    WHERE t1.store_id=2 ORDER BY t1.timestamp; 
+------+----------+-------------------+ 
| id | store_id | myTimeDiffSeconds | 
+------+----------+-------------------+ 
| 2 |  2 |     0 | 
| 4 |  2 |    11 | 
| 6 |  2 |     3 | 
+------+----------+-------------------+ 
3 rows in set (0.00 sec) 

的另一种方式是使用会话变量来保存前一次,但在这种情况下,我们需要首次获得最小时间戳

mysql> select min(p.timestamp) into @prev_time from print p where p.store_id=2; 
Query OK, 1 row affected (0.00 sec) 

mysql> select id, 
      store_id, 
      timestampdiff(second,@prev_time,timestamp) myTimeDiffSeconds, 
      @prev_time:=timestamp 
    from print 
    where store_id=2 order by timestamp; 
+------+----------+-------------------+---------------------+ 
| id | store_id | myTimeDiffSeconds | @prev_time:=t  | 
+------+----------+-------------------+---------------------+ 
| 2 |  2 |     0 | 2013-03-01 00:00:01 | 
| 4 |  2 |    11 | 2013-03-01 00:00:12 | 
| 6 |  2 |     3 | 2013-03-01 00:00:15 | 
+------+----------+-------------------+---------------------+ 
3 rows in set (0.00 sec) 

index(timestamp,store_id)将使查询执行得更好。