多个Join或子​​查询查询优化

时间:2009-10-06 12:53:07

标签: sql mysql optimization profiling

我有这个查询,对于给定的案例在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 个答案:

答案 0 :(得分: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,您还可以 尝试 加入,而不是使用Exists,

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