2012-10-23 36 views
0

此過程正在運行,但需要5分鐘才能運行。有沒有更快,更簡單的方法?複雜查詢的MySQL存儲過程需要5分鐘

我有一張表,其中包含檢查列表。隨後的檢查將在晚些時候插入同一張表中。後續檢查具有相同的serial_number,但具有不同的date_stamp。我需要找出哪些檢查沒有完成跟蹤檢查。

所以首先我得到所有type_due = 3的serial_number,並且沒有標記爲inspection_completed。

然後,從這個serial_numbers的列表中,我檢查是否有一個檢查是否有一個相同的serial_number在稍後的date_stamp被標記爲inspection_completed。

所以這是一個選擇只有當別的東西存在;如果第二個查詢中的結果中有相同的serial_number,更高的日期和不爲空的inspection_completed值,則會消除第一個查詢中的結果池。

每次運行此查詢時,我都會截斷Inspections_due表,因爲添加到Inspections表中的新跟進檢查將使Inspections_due表中的某些結果不再有效。

第一個查詢大約有9,000個結果。總的來說,編寫另一個查詢以刪除Inspections_due表中的無效結果並且每次運行此查詢時只將新記錄添加到Inspections_due中,可能會更快。

注:我試過選擇計數(*)而不是選擇存在,但沒有太大的速度差異。

任何建議將是偉大的!由於

CREATE PROCEDURE create_due_inspections() 
BEGIN 

    DECLARE done INT DEFAULT FALSE; 
    DECLARE iid int(10); #unique inspection id 
    DECLARE sn VARCHAR(16); #serial number 
    DECLARE dt date; #date_stamp 
    DECLARE `result` int; 

    DECLARE cur1 CURSOR FOR SELECT inspection_id, serial_number, date_stamp FROM 
     Inspections where type_due = '3' and inspection_completed is null; 

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 

    TRUNCATE TABLE `Inspections_due`; # clean out the old results 

    OPEN cur1; 

    read_loop: LOOP 

    FETCH cur1 INTO iid,sn,dt; 
    IF done THEN 
     LEAVE read_loop; 
    END IF; 

    SET `result` := (select exists(Select inspection_id from Inspections 
where serial_number = sn and date_stamp > dt and inspection_completed is not null)); 

    IF `result` THEN 
     insert into Inspections_due values(iid); 
    END IF; 

    END LOOP; 

    CLOSE cur1; 
END; 

回答

1

你應該避免光標,並與臺工作:

INSERT into Inspections_due 
SELECT 
     inspection_id as iid 
FROM 
     Inspections I1 
where 
     type_due = '3' and inspection_completed is null 
     and exists(
      Select inspection_id 
      from Inspections I2 
      where I2.serial_number = I1.serial_number 
       and I2.date_stamp > I1.date_stamp 
       and inspection_completed is not null)) 

而且替換由內連接存在子查詢:

SELECT distinct 
     inspection_id as iid 
FROM 
     Inspections I1 
inner join 
     Inspections I2 
     on 
       I2.serial_number = I1.serial_number 
       and I2.date_stamp > I1.date_stamp 
       and inspection_completed is not null 
+0

danihp,謝謝!我明白你要去哪裏,這樣做更有意義。到目前爲止,我得到0插入的結果,但我會繼續擺弄它。 –

+0

@i_a,我已將您的光標循環轉換爲單個sql語句,抱歉,因爲可能包含一些小錯誤,但保持操作意義。 – danihp

+0

啊,我需要在存在之前加上「不」,因爲我需要反面,所有檢查都沒有一個完整的記錄。我從50,000條記錄中獲得了9000條結果,所以這可能現在正在工作,需要進行一些現場檢查以確保。再次感謝您的回覆。 –