2

我正在使用 MySQL 存储某些事件,其中包含有关谁完成了此事件以及某个事件发生时的时间戳的信息。我目前将这些信息存储在两个表中,“Cycles”和“Movement_Load”。

现在我想将“Movement_Load”中包含的信息附加到“Cycles”表中。此操作的好处是我将所有相关信息存储在一个表中。

表周期:

(1, '00:50:c2:63:10:1a',  1351508100,    1351508200, 'center', 0, 0);

表运动_负载:

(1, 'move_sensor1',  1351508090,     'movement start'), 
(2, 'move_sensor1',  1351508120,     'movement end'),   -- 20 not 30, because it starts at 1351508100 
(3, 'move_sensor1',  1351508140,     'movement start'), 
(4, 'move_sensor1',  1351508170,     'movement end'),   -- 30 
(5, 'move_sensor1',  1351508190,     'movement start'),   
(6, 'move_sensor1',  1351508210,     'movement end'),   -- 10 not 20, because it ends at 1351508200
                                                        -- movement sum is 60
(7,'load_sensor1',  1351508130,     'load start'), 
(8,'load_sensor1',  1351508180,     'load end'), -- 50 
(9,'load_sensor1',  1351508185,     'load start'), 
(10,'load_sensor1', 1351508220,     'load end')  -- 15 not 35, because it ends at 1351508200
                                                  -- load sum is 65

结果应如下所示,运动 (60) 和负载 (65) 现在存储在此表中:

(1, '00:50:c2:63:10:1a',  1351508100,    1351508200, 'center', 60, 65 )

要解决这个问题,请看我准备的小提琴:http ://sqlfiddle.com/#!2/b1113

4

1 回答 1

2
UPDATE Cycles
SET movement_time =
    (SELECT IFNULL(SUM(CASE event
                       WHEN 'movement start' THEN -timestamp
                       WHEN 'movement end'   THEN timestamp
                       ELSE                       0
                       END), 0)
            + CASE (SELECT event
                    FROM Movement_load
                    WHERE timestamp BETWEEN Cycles.startTimestamp
                                        AND Cycles.endTimestamp
                      AND event LIKE 'movement %'
                    ORDER BY timestamp
                    LIMIT 1)
              WHEN 'movement end' THEN -Cycles.startTimestamp
              ELSE                     0
              END
            + CASE (SELECT event
                    FROM Movement_load
                    WHERE timestamp BETWEEN Cycles.startTimestamp
                                        AND Cycles.endTimestamp
                      AND event LIKE 'movement %'
                    ORDER BY timestamp DESC
                    LIMIT 1)
              WHEN 'movement start' THEN Cycles.endTimestamp
              ELSE                       0
              END
     FROM Movement_Load
     WHERE timestamp BETWEEN Cycles.startTimestamp
                         AND Cycles.endTimestamp)

(类似的load

于 2013-03-10T11:02:13.763 回答