有没有办法优化下面的查询?它需要查看多个表。提前感谢您的帮助,非常感谢。相关架构:
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
)
)
)
编辑:短是客户选择一辆自行车,这会选择适合的产品,无论是产品本身还是产品选项变体。请注意此代码有效,我只想知道是否有优化它的方法。