2

I am using MySQL to store certain events with information about who has done this event and the timestamps when a certain event took place. I have these informations stored in two tables at the moment, "Cycles" and "Movement_Load".

Now i want to append the information contained in "Movement_Load" to the table "Cycles". The benefit of this operation is that i have all relevant information stored in one table.

Table Cycles:

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

Table Movement_Load:

(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

The result should look like this, movement (60) and load (65) are now stored in this table:

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

To solve this problem, please see my prepared fiddle: 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 に答える