mysql在时间戳中重叠了两个表

时间:2013-03-14 10:02:31

标签: mysql sql sqlite timestamp

我在MySQL中有两个表。在每个表中,保存了具有MAC地址和状态区域信息的设备。

这些状态确实在某些时间戳(startTime,endTime)及其持续时间(endTime-startTime)开始和结束,并且由某些id引起。

现在我想找到以天为单位的某些事件“move”和“load”之间的重叠,如下所示:

sum of time, when movement took place (value in the fiddle: 421)
sum of time, when load took place (value in the fiddle: 520)
sum of time, when movement and load took place (value in the fiddle: 391)

查询结果应如下所示:

ID                  DATE                            ALL_MOVEMENT    ALL_LOAD    LOAD_MOVEMENT
00:50:c2:63:10:1a   October, 29 2012 00:00:00+0000  421             520         391
00:50:c2:63:10:1a   February, 22 2013 00:00:00+0000 421             520         391
00:50:c2:63:10:1b   February, 22 2013 00:00:00+0000 181             220         181

我在这里准备了一个小提琴:http://sqlfiddle.com/#!2/c210c

更新:在这里可以看到一个提供我想要的东西的小提琴:

http://sqlfiddle.com/#!2/31b94/1

2 个答案:

答案 0 :(得分:4)

我真的不明白数据集是如何与结果集相关联的,但在我看来,你想要或多或少的东西......

 SELECT m.id
      , DATE(FROM_UNIXTIME(m.starttime))Date,SUM(m.duration) all_movement
      , SUM(l.duration) all_load
   FROM move_table m
   JOIN load_table l
     ON l.id = m.id
    AND l.endtime > m.starttime
    AND l.starttime < m.endtime
  GROUP 
     BY m.id
      , DATE(FROM_UNIXTIME(m.starttime));
 +-------------------+------------+--------------+----------+
 | id                | Date       | all_movement | all_load |
 +-------------------+------------+--------------+----------+
 | 00:50:c2:63:10:1a | 2012-10-29 |          391 |      520 |
 | 00:50:c2:63:10:1a | 2013-02-22 |          391 |      520 |
 | 00:50:c2:63:10:1b | 2013-02-22 |          181 |      220 |
 +-------------------+------------+--------------+----------+

顺便说一下,duration在这种情况下似乎是多余的,因为(例如)SUM(m.endtime-m.starttime)会得到相同的结果。

答案 1 :(得分:3)

我不知道如何解决'load'和'no load'之间的区别,因为数据库中没有关于它的真实信息 - 但也许这是你玩的起点。

SELECT a.ID, a.D, SUM(a.MOVETIME) AS ALL_MOVEMENT, SUM(a.LOADTIME) AS ALL_LOAD
FROM (
SELECT ID, DATE(FROM_UNIXTIME(startTime)) AS d, SUM(duration) AS MOVETIME, 0 AS LOADTIME
FROM move_table
GROUP BY ID, DATE(FROM_UNIXTIME(startTime))
UNION
SELECT ID, DATE(FROM_UNIXTIME(startTime)) AS d, 0 AS MOVETIME, SUM(duration) AS LOADTIME
FROM load_table
GROUP BY ID, DATE(FROM_UNIXTIME(startTime))) AS a
GROUP BY a.ID, a.D