我有2個表:Mysql的集團和SUM優化
CREATE TABLE IF NOT EXISTS `products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`categoryId` int(10) unsigned DEFAULT NULL,
`parentId` int(10) unsigned DEFAULT NULL,
`barcode` varchar(255) DEFAULT NULL,
`code` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_products_product_categories1_idx` (`categoryId`),
KEY `fk_products_products1_idx` (`parentId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=71521 ;
CREATE TABLE IF NOT EXISTS `inventory` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`depotId` int(10) unsigned NOT NULL,
`productId` int(10) unsigned NOT NULL,
`remain` int(11) DEFAULT NULL,
`remain2` int(10) unsigned DEFAULT NULL,
`updatedDateTime` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_inventory_depots1_idx` (`depotId`),
KEY `fk_inventory_products1_idx` (`productId`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=89291 ;
請幫我優化下面的查詢(應該添加哪些指標來提高性能),查詢花費0.2578秒(MySQL的使用指數fk_inventory_depots1_idx ),當移除AND i.depotId = 3時,查詢耗時0.5484秒。 EXPLAIN查詢顯示Extra:使用where;使用臨時;使用文件排序
SELECT `p`.* , SUM(i.remain) AS `remain` , SUM(i.remain2) AS `remain2`
FROM `products` AS `p`
LEFT JOIN `inventory` AS `i` ON p.id = i.productId
WHERE remain != 0 AND i.depotId = 3
GROUP BY `p`.`id`
ORDER BY `p`.`id` DESC
LIMIT 50
上創建'inventory'表'(的productId,保持,depotId)'一個索引。希望這有助於... – Meherzad 2013-04-26 05:36:53