0

有没有办法优化下面的查询?它需要查看多个表。提前感谢您的帮助,非常感谢。相关架构:

CREATE TABLE `variant_bikes` (
  `variant_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  `bike_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`variant_id`,`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `product_bikes` (
  `product_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  `bike_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`product_id`,`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `cart_products` (
  `product_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`product_id`),
) ENGINE=MyISAM AUTO_INCREMENT=95 DEFAULT CHARSET=utf8;

CREATE TABLE `cart_product_options` (
  `option_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `product_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`option_id`),
) ENGINE=MyISAM AUTO_INCREMENT=9040 DEFAULT CHARSET=utf8;

CREATE TABLE `cart_product_option_variants` (
  `variant_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `option_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`variant_id`),
) ENGINE=MyISAM AUTO_INCREMENT=9040 DEFAULT CHARSET=utf8;

SQL是:

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

编辑:短是客户选择一辆自行车,这会选择适合的产品,无论是产品本身还是产品选项变体。请注意此代码有效,我只想知道是否有优化它的方法。

4

2 回答 2

0

试试这个:

select * from product_bikes PB
         join cart_product_options CPO on PB.PRODUCT_ID = CPO.PRODUCT_ID
         join cart_product_option_variants CPOV on CPO.OPTION_ID = CPOV.OPTION_ID
where PB.product_id = $product[product_id]
and CPOV.variant_id  in    ( $valid_variants_list )
于 2012-08-10T17:20:32.610 回答
0

虽然我的问题的性质发生了一些变化,加入策略有效,但它是最好的答案吗?即,它是否解决了我原来的问题,即它被优化为两种工作:

select distinct p.product_id from cscart_products p 
    left join product_bikes pb on p.product_id = pb.product_id and pb.bike_id = 111
    left join cscart_product_options po on po.product_id = p.product_id
    left join cscart_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 = 111
    where pb.bike_id = 111 or vb.bike_id = 111

然而,这导致没有明显的速度提升。(有时它会更快返回,有时可能由于当时的服务器负载而变慢)。

于 2012-08-10T17:58:48.027 回答