0

我在商店里有 500 个信息亭,并且有一个表格可以按商店 ID 跟踪每张印刷品的时间戳。我需要生成一个记录集,以秒为单位提供打印之间的时间。所有这些数据都存储在一个表中。每次打印都会插入一条记录,其中包含商店 ID 和时间戳。

表名 = 打印
ID store_id 时间戳
1 1 2013-3-1 00:00:01 2 2 2013-3-1 00:00:01
*
3 3
2013-3-1 00:00:01 4 2 2013-3- 1 00:00:12 *
5 3 2013-3-1 00:00:06
6 2 2013-3-1 00:00:15 *

我需要在所有商店#2 打印之间以秒为单位缩短时间。* 是为了方便您找到我需要比较的记录。

记录集结果如下:

id store_id myTimeDiffSeconds
2 2 0
4 2 11
6 2 3

这需要简单快速。我可以在没有临时表的情况下执行此操作吗?

4

1 回答 1

2

您可以通过两种方式编写查询
1. 使用相关查询
2. 使用会话变量

第一个正是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)

(timestamp,store_id) 上的索引将使查询执行得更好。

于 2013-03-27T10:25:01.430 回答