相关子查询(在同一个表上)

时间:2014-03-26 22:56:37

标签: mysql correlated-subquery

我有一个表可以跟上房间中设备状态的变化,并且需要编写一个查询,列出自上次状态更改以来的时间量。该表由字段new_state,prev_state,room,timestamp组成。我的最新尝试是

SELECT a.room, a.prev_state, a.new_state, 
timediff(a.timestamp, b.timestamp) from   status_change as a
(SELECT b.timestamp from status_change as b 
 WHERE a.timestamp<b.timestamp and a.room=b.room
 ORDER BY b.timestamp DESC LIMIT 1)

希望这传达了我想要完成的事情。

由于

3 个答案:

答案 0 :(得分:1)

SELECT t2.timestamp-t1.timestamp 
FROM state_change AS t1 
JOIN (SELECT * FROM state_change) AS t2 
ON t1.new_state = t2.prev_state AND t1.timestamp < t2.timestamp

答案 1 :(得分:0)

试试这个(你应该在它上面放一个主键,特别是出于性能原因)

SELECT status_change.*
 , previous.timestamp AS earlier_timestampe
 , TIMEDIFF(status_change.timestamp, previous.timestamp) AS time_between
FROM status_change 
LEFT JOIN status_change AS previous
  ON status_change.room = previous.room
    AND status_change.timestamp > previous.timestamp
LEFT JOIN status_change AS inbetweener
  ON status_change.room = inbetweener.room
    AND inbetweener.timestamp BETWEEN previous.timestamp AND status_change.timestamp
WHERE inbetweener.room IS NULL
ORDER BY status_change.timestamp DESC;

答案 2 :(得分:0)

除了提供的查询之外,我强烈建议根据每个设备的每个新条目的添加添加一个简单的触发器。基本上有两列lastUpdateID,UpdateIDBeforeThat。

然后在更新触发器中,执行类似

的操作
update RoomTable
   set UpdateIDBeforeThat = lastUpdateID,
       lastUpdateID = newIDJustInserted
   where
      room = RoomBasedOnInsertedRecord
     and currentRoomStatus != InsertedRecordRoomStatus

然后,您要进行比较的查询可能非常简单 选择

select
      r.roomid,
      c1.date/time,
      c2.date/time,
      calc-diff of date/time,
      any other fields from c1 or c2 respectively
   FROM 
      rooms r
         LEFT JOIN status_change c1
            on r.lastUpdateID = c1.ID
         left join status_change c2
            on r.UpdateBeforeThat = c2.ID