2014-08-27 37 views
0

我們的一些SQL查詢需要3個多小時才能執行,考慮到我們的數據庫目前大約有5000個條目,這確實很長。SQL查詢佔用時間超過1小時

這裏兩個最長聲明:

/* Alte Jobs anzeigen */ 

update vwr_synch.listings set vwr_synch.listings.Alt="alt" 
where vwr_synch.listings.JobKey not in (select vwr_synch.jobs.JobKey from vwr_synch.jobs) 
; 

update vwr_synch.listings set vwr_synch.listings.Alt="alt" where vwr_synch.listings.VWRStatus="NoJobs" or vwr_synch.listings.VWRStatus="Problem" 
; 


update vwr_synch.listings set vwr_synch.listings.Alt=NULL 
where vwr_synch.listings.VWRStatus="Active" and vwr_synch.listings.VWRRetry!="0" and vwr_synch.listings.Alt="alt" 
; 


/* Neue Jobs anzeigen */ 

update vwr_synch.jobs set vwr_synch.jobs.NeuAlt="Neu" 
where vwr_synch.jobs.JobKey not in (select vwr_synch.listings.JobKey from vwr_synch.listings) and (vwr_synch.jobs.`Status`="Active" and vwr_synch.jobs.Retry="0") 
; 
+0

是你正在更新的那些視圖嗎?這是什麼vwr前綴是什麼? – Donal 2014-08-27 11:42:58

+0

@Donal沒有vwr前綴是由應用程序創建的 – 2014-08-27 11:48:09

回答

3

示例代碼中有多個語句,所以我就重點放在了第一位。

我更喜歡not in,因爲使用NULL的語義,雖然有證據表明not in可能更有效(請參閱評論中的鏈接)。這是第一個查詢:

update vwr_synch.listings 
    set vwr_synch.listings.Alt = 'alt' 
    where vwr_synch.listings.JobKey not in (select vwr_synch.jobs.JobKey from vwr_synch.jobs); 

我將其更改爲:

update vwr_synch.listings l 
    set l.Alt = 'alt' 
    where not exists (select 1 from vwr_synch.jobs.JobKey jk where jk.JobKey = l.JobKey); 

然後,這有效地工作,你需要vwr_synch.jobs.JobKey(JobKey)的索引。

接下來的兩個語句是:

update vwr_synch.listings l 
    set l.Alt = 'alt' 
    where l.VWRStatus in ('NoJobs', 'Problem'); 

update vwr_synch.listings l 
    set l.Alt = NULL 
    where l.VWRStatus = 'Active' and l.VWRRetry <> '0' and l.Alt = 'alt'; 

對於這些,你想對vwr_synch.listings(VWRStatus, Alt, VWRRetry)的索引。

+0

根據[本文](http://explainextended.com/2009/09/18/not-in-vs-not-exists-vs-left-join- is-null-mysql /),'NOT EXISTS'實際上比'NOT IN'慢。我會讓索引成爲你答案的主要內容。 – Arth 2014-08-27 11:47:53

+0

另外,使用where子句來確定你需要的索引。看看你的SQL我看到這些列上需要的索引:vwr_synch.listings.JobKey,vwr_synch.jobs.JobKey,vwr_synch.listings.VWRStatus,vwr_synch.listings.VWRRetry,vwr_synch.listings.Alt,vwr_synch.jobs.Status,vwr_synch。 jobs.Retry – Dave 2014-08-27 11:49:08

+0

@Arth。 。 。我實際上更喜歡'NOT IN',因爲語義更符合人們的期望。當子查詢中的某個元素爲假時,「NOT IN」從不返回true。我修改了答案,但我在博客中對這個評論感到擔憂:「很難說出這個確切的原因......」。 – 2014-08-27 11:54:10