2009-10-06 86 views
0

我有這個疑問,其執行1或2秒爲一個給定的情況:多加入或子查詢的查詢優化

Select Count(*) as qtty 
    From event e 
    Join org o On o.orgID = e.orgID 
    Join venue v On v.venueID = e.venueID 
    Where Match(e.name, e.description) Against ($keywords) 
     And e.site_id = $site_id 
     And e.display <> 0</code> 

它計算的行建立分頁。當我按事件類型過濾介紹(類型涉及多對多事件)查詢開始服用沒有少於45秒:

And Exists ( 
     Select ete.id 
     From event_type_to_event ete 
     Where ete.event_id = e.eventID 
     And ete.event_type_id = $category)</code> 

我也試圖與event_type_to_event一個加入,但它更慢。
有什麼建議嗎?

注:解決。使用索引,查詢執行時間縮短到不到一秒。

+1

請貼EXPLAIN查詢 – 2009-10-06 13:00:05

回答

1

我懷疑你需要在表event_type_to_event列event_type_id添加一個索引,但如果已經有一個索引存在,那麼請嘗試以下操作:

Select Count(*) as qtty 
From event e 
    Join org o On o.orgID = e.orgID 
    Join venue v On v.venueID = e.venueID 
Where Match(e.name, e.description) Against ($keywords) 
    And e.site_id = $site_id 
    And e.display <> 0 
    And Exists 
     (Select * From event_type_to_event 
     Where event_id = e.eventID 
      And event_type_id = $category) 

如果EVENT_ID是表event_type_to_event你的PK也可以嘗試聯接,而不是使用存在,

Select Count(*) as qtty 
From event e 
    Join org o On o.orgID = e.orgID 
    Join venue v On v.venueID = e.venueID 
    Join event_type_to_event t 
     On t.event_id = = e.eventID 
Where Match(e.name, e.description) Against ($keywords) 
    And e.site_id = $site_id 
    And e.display <> 0 
    And t.event_type_id = $category 
+0

謝謝你的結果!我不得不承認,這是我第一次看到使用指數的區別! (這樣的DB新手) 無論如何,第二個查詢將無法正常工作,因爲event_type_to_event是一個'多對多'的表,所以它也應該按事件id分組,但我也試過,沒有索引,它是比子查詢慢。謝謝! – Petruza 2009-10-06 14:52:03