2009-10-06 87 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