首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >mySql TimeDiff在单个表的行中的TimeStamp之间

mySql TimeDiff在单个表的行中的TimeStamp之间
EN

Stack Overflow用户
提问于 2013-03-26 00:55:38
回答 1查看 779关注 0票数 0

我在商店里有500个售货亭,并且有一个表根据商店ID跟踪每个打印的时间戳。我需要生成一个记录集,给出打印之间的时间间隔(以秒为单位)。所有这些数据都存储在一个表中。为每个打印插入一条记录,其中包含商店ID和timeStamp。

表名=打印

id  store_id  timestamp

2013-3-1 00:01:01:00:01:00:01

2013-3-1 00:01**2: 00:00:01 **

2013-3-1 00:01:00:01

2013-3-1 00:12:4-2:00:00-12**

2013-3-1 00:06:00:06

2013-3-1 00:15:6-2:00:00-11:00**

我需要拉取所有商店2号指纹之间的时间。*是为了便于您找到我需要比较的记录。

RecordSet结果如下:

id  store_id  myTimeDiffSeconds

*0

4/2* 11

6/2*3

这需要简单和快速。我可以在没有临时表的情况下做到这一点吗?

EN

回答 1

Stack Overflow用户

发布于 2013-03-27 18:25:01

您可以通过两种方式编写查询

  1. using correlated
  2. using session variable

第一个正是ethrbunny指出的

代码语言:javascript
运行
复制
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)

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

代码语言:javascript
运行
复制
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 on (timestamp,store_id)将使查询执行得更好。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15620476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档