MySQL查询优化的派生&子查询组合查询

时间:2014-07-16 07:01:33

标签: mysql query-optimization high-traffic

在使用派生表和子查询的服务器上运行以下类型的查询。约束是子查询是根据当前情况从多个模块生成的,因此无法将其真正转换为连接组合。

请建议优化查询的可能解决方案

 SELECT COUNT(1) 
 AS total 
 FROM member tlb_m
 where tlb_m.active = 1 
 and tlb_m.rank > 0 
 and tlb_m.member_id not in (5735,134,241,1055,348,272,476,43,7,804,7548,90,229,346,40895) 
 and tlb_m.type = 'M' 
 and (tlb_m.hometown_list_id in 
  (SELECT l2.list_id  
    FROM ((
      SELECT t12.list_id 
      from list_tree_idx t12 
      INNER JOIN list_tree_idx t11 
      ON t12.list_parent_id=t11.list_id 
      where t11.list_parent_id='205546' 
    ) UNION ALL (
      SELECT list_id 
      from list_tree_idx 
      where list_parent_id='205546'
    ) ) as l2 
  ) or tlb_m.hometown_list_id = 205546
) 

1 个答案:

答案 0 :(得分:0)

我建议使用closure table进行最佳分层查询。 例如,有一个包含ANCESTOR_ID,CHILD_ID和DEPTH列的闭合表,您的查询将像这样

SELECT COUNT(1) AS total 
  FROM member AS tlb_m
  LEFT JOIN hometown_closure AS c ON c.child_id = tlb_m.hometown_list_id
  where tlb_m.active = 1 
    and tlb_m.rank > 0 
    and tlb_m.member_id not in (5735,134,241,1055,348,272,476,43,7,804,7548,90,229,346,40895) 
    and tlb_m.type = 'M' 
    and c.ancestor_id = 205546