2012-08-10 66 views
0

有人告诉我,使用加入到优化这个查询:优化MySQL查询多个表中,使用VS JOIN(或其他方式)和性能

select distinct p.product_id 
from cart_products p 
    left join product_bikes b on p.product_id = b.product_id where bike_id = $bike_id 
or 
p.product_id in (
    select product_id from cart_product_options where option_id in (
     select option_id from cart_product_option_variants where variant_id in (
      select variant_id from variant_bikes where bike_id=$bike_id 
     ) 
    ) 
) 

然而,使用加入似乎给没有速度提升可言:

select distinct p.product_id from cart_products p 
    left join product_bikes pb on p.product_id = pb.product_id and pb.bike_id = $bike_id 
    left join cart_product_options po on po.product_id = p.product_id 
    left join cart_product_option_variants pov on pov.option_id = po.option_id 
    left join variant_bikes vb on vb.variant_id = pov.variant_id and vb.bike_id = $bike_id 
    where pb.bike_id = $bike_id or vb.bike_id = $bike_id 

根据服务器的负载电流表大小他们都很快进行,但是当有很多更多的产品,产品的选择等附加组件的这部分确实导致速度变慢。我只是想知道以什么方式让mysql运行这个查询最快。有人可以说一个事实JOINS是优越的答案或知道任何其他技巧来加速?

+1

您能否验证JOIN条件和WHERE子句中使用的所有字段是否定义了某种索引? – 2012-08-10 18:21:11

+0

是的,我可以验证。所有连接条件都在主键上,否则索引。主要问题是,即使商店中只有1000件左右的产品,product_bikes和variant_bikes也会有超过100万行,我们希望有超过10,000件商品。 – Wolfe 2012-08-10 18:21:53

回答

1

Mysql在处理“in”语句中的子查询方面做得很差。相关子查询中“存在”的使用速度要快得多,特别是如果内部表中用于关联的字段有索引。

尝试类似:

select distinct p.product_id 
from cart_products p left join 
    product_bikes b 
    on p.product_id = b.product_id 
where bike_id = $bike_id or 
     exists (select * 
       from cart_product_options cpo 
       where cpo.productid = p.productid and 
        exists (select option_id 
          from cart_product_option_variants cpov 
          where cpo.option_id = cpov.option_id and 
            exists (select variant_id 
              from variant_bikes vb 
              where vb.variant_id = cpov.variant_id and 
               bike_id=$bike_id 
              ) 
          ) 
      ) 

这应该工作。 。 。但你确实有很多嵌套的子查询。

+0

谢谢,这个表现会比JOIN更好还是加入最后? – Wolfe 2012-08-10 19:06:29

+1

它应该比“in”表现更好。我怀疑连接版本有创建大量额外的行的问题,因为表之间的所有连接。换句话说,他们可能都有不好的表现,但出于不同的原因。 – 2012-08-10 19:22:43