优化多表搜索

时间:2012-08-10 16:51:27

标签: php mysql

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

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

编辑:简短是客户选择自行车,然后选择适合产品本身或产品选项变体的产品。请注意,此代码有效,我只想知道是否有一种优化方法。

2 个答案:

答案 0 :(得分:1)

试试这个:

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 )

答案 1 :(得分: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
然而,这导致没有明显的速度提升。 (有时它会更快地返回,其他时间可能由于当时的服务器负载而变慢)。