有什麼方法可以優化下面的查詢?它需要查看多個表。非常感謝您的幫助。相關模式:優化多表搜索
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
)
)
)
編輯:短髮是客戶選擇一輛自行車,這其中選擇適合的產品,無論是產品本身還是產品選項變種。注意這個代碼的作品,我只是想知道是否有一種方法來優化它。
連接是您的問題的解決方案 http://dev.mysql.com/doc/refman/5.1/en/join.html – chicharito 2012-08-10 17:10:49
JOIN是正確的策略。按表開始連接一個表,並在每個階段添加一個過濾器。 – 2012-08-10 17:22:55