0

有人告诉我使用连接来优化这个查询:

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 是最好的答案,或者知道任何其他加快速度的技巧吗?

4

1 回答 1

0

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
                                           )
                             )
              ) 

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

于 2012-08-10T18:41:36.807 回答