簡體   English   中英

關聯子查詢(在同一表上)

[英]Correlated Subquery (on same table)

我有一個表,可以跟蹤房間中設備狀態的變化,並且需要編寫查詢以列出自上次狀態變化以來的時間量。 該表由以下字段組成: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)

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

謝謝

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

試試看(您應該在上面放一個主鍵,尤其是出於性能原因)

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;

除了提供的查詢之外,我強烈建議根據每個設備的每個新條目的添加來添加一個簡單的觸發器。 基本上兩列為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM