Is there any way to optimize the query below? It requires looking through multiple tables. Thank you in advance for your help it is appreciated. Relevant schema:
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;
And SQL is:
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
)
)
)
Edit: Short is a customer selects a bike and this selects the products which fit, either the product itself or the product option variants. Note this code works I just want to know if there is a way to optimize it.
Though the nature to my question changed a bit the join strategy works, but is it the best answer? i.e. does it resolve my original question of it being optimized as both work:
This resulted in no noticeable speed boost however. (sometimes it would return quicker, other times slower probably due to server load at the time).