2014-03-26 228 views
0

我有與室內設備狀態變化保持了一個表,需要編寫一個查詢,列出了自上一次狀態改變的時間量。該表由字段new_state,prev_state,房間,時間戳組成。我最近的嘗試是相關子查詢(在同一個表)

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) 

希望傳達我正在努力實現的目標。

感謝

+0

什麼是'主Key'爲'status_change'表? – Edper

+0

status_change沒有主鍵。如果我要添加一個,它將是空間,時間戳 - 這將是一個唯一的鍵 – user3466409

回答

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; 
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 
+0

我需要的是行之間的增量。例如,如果第1行的時間戳爲13:00,第2行的時間戳爲14:00 - 我需要一個查詢來列出自上次輸入以來的時間量的所有行。所以在這個例子中,查詢會產生第2行的信息和1點的timediff(即14:00到13:00)。希望這更清楚。 – user3466409

+0

新狀態是否保存到新行中?導致前面的行的new_state是新行的prev_state? – Smokie

+0

是的,這是正確的 – user3466409

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 
+0

謝謝 - 一位同事還建議使用rownum - 您是否意識到這種方法存在任何問題? – user3466409

+0

@ user3466409,不知道rownum,但是如果通過status_change表中的自動增量列,它應該確保通過實際密鑰的有效鏈接。 – DRapp