我有 2 张桌子:
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: Using 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