簡體   English   中英

用於復雜查詢的MySQL存儲過程需要5分鍾

[英]MySQL Stored Procedure for Complex Query takes 5 minutes

此過程正在運行,但是需要5分鍾才能運行。 有沒有更快,更簡單的方法?

我有一張表,其中包含檢查清單。 以后在同一表中插入了后續檢查。 后續檢查具有相同的序列號,但具有不同的date_stamp。 我需要找出哪些檢查尚未完成跟進檢查。

所以首先我要獲取所有type_due = 3且未標記為inspection_completed的序列號。

然后,從該序列號列表中,我正在檢查是否在以后的date_stamp上進行了具有相同序列號的檢查,該檢查被標記為inspection_completed。

因此,只有在存在其他條件時才是選擇。 如果第二個查詢中的結果具有相同的serial_number,更大的日期和Inspection_completed值不為null,則消除第一個查詢中的結果池。

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

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

注意:我嘗試使用Select count(*)代替Select Exists,但是速度差異不大。

任何建議都很好! 謝謝

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;

您應該避免使用游標並使用set

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

暫無
暫無

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

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