【发布时间】:2011-07-18 11:53:11
【问题描述】:
我有一个选择订单的查询,对于每个订单,我需要获取其中包含的产品列表以及每个产品的汇总数量。
目前速度很慢(我的设置需要 10 秒),我需要加快速度。
更新:不能切换到 MyISAM,我需要交易
目前的查询是这样的:
SELECT `Order`.*, `Product`.`id`, `Product`.`msrp`, SUM(`OrderItem`.`quantity`) AS sum
FROM `orders` AS `Order`
LEFT JOIN `order_items` AS `OrderItem` ON (`OrderItem`.`order_id` = `Order`.`id`)
LEFT JOIN `product_variations` AS `ProductVariation` ON (`OrderItem`.`product_variation_id` = `ProductVariation`.`id`)
LEFT JOIN `products` AS `Product` ON (`ProductVariation`.`product_id` = `Product`.`id`)
WHERE 1 = 1
GROUP BY `Order`.`id`, `Product`.`id`
ORDER BY `Order`.`created` DESC
LIMIT 20;
解释:
架构(截断,只剩下必填字段):
CREATE TABLE `orders` (
`id` int(11) NOT NULL auto_increment,
`created` timestamp NOT NULL default CURRENT_TIMESTAMP,
`customer_comments` text NOT NULL,
PRIMARY KEY (`id`),
KEY `created` (`created`),
KEY `id_created` (`id`,`created`),
) ENGINE=InnoDB
CREATE TABLE `order_items` (
`id` int(11) NOT NULL auto_increment,
`order_id` int(11) NOT NULL,
`product_variation_id` int(11) NOT NULL,
`type` enum('First','Second') default NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `item_UNIQUE` (`order_id`,`product_variation_id`,`type`),
KEY `fk_order_items_product_variations1` (`product_variation_id`),
CONSTRAINT `fk_order_items_orders1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_order_items_product_variations1` FOREIGN KEY (`product_variation_id`) REFERENCES `product_variations` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB
CREATE TABLE `product_variations` (
`id` int(11) NOT NULL auto_increment,
`product_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_product_variations_products1` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
) ENGINE=InnoDB
CREATE TABLE `products` (
`id` int(11) NOT NULL auto_increment,
`msrp` decimal(5,2) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB
服务器是 MySQL 5.0.77,表是 InnoDB。
orders 大约有 75k 条记录,order_items 160k 条记录,product_variations 140k 条记录,product - 300 条记录。
感谢任何帮助。
【问题讨论】:
标签: mysql performance select group-by