我正试图阻止mysql在此查询中创建临时表
SELECT `vendor_id`,SUM(`qty`) AS `qty`
FROM `inventory_transactions`
WHERE `inventory_transactions`.`date`
BETWEEN '2018-10-21 00:00:00' AND '2018-10-22 23:59:59'
GROUP BY `vendor_id`
我尝试使用SELECT DISTINCT
,MIN(vendor_id)
,MAX(vendor_id)
重新排列索引,并添加COUNT(*)
列以尝试查看是否会使用要排序的索引。
我在每个变体以及单个索引中都有ix(date,type,vendor_id)
。
我似乎无法弄清为什么mysql一直尝试从临时表中进行排序,所以它不使用临时表的唯一方法是如果我按date
列进行分组,而不是我想要的。
任何人都对如何解决有什么见识?
表架构
CREATE TABLE `transactions` (
`id` int(11) NOT NULL,
`vendor_id` int(11) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
`unit_cost` decimal(10,2) NOT NULL,
`qty` decimal(11,2) DEFAULT NULL,
`location_id` int(11) NOT NULL,
`date` timestamp NOT NULL,
PRIMARY KEY (`id`),
KEY `location_id` (`location_id`),
KEY `type` (`type`),
KEY `vendor_id` (`vendor_id`) USING BTREE,
KEY `date` (`date`,`vendor_id`,`type`) USING BTREE,
CONSTRAINT `transactions_ibfk_1` FOREIGN KEY (`location_id`) REFERENCES `locations` (`id`),
CONSTRAINT `transactions_ibfk_3` FOREIGN KEY (`vendor_id`) REFERENCES `vendors` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
解释
+----+-------------+------------------------+------------+-------+----------------------+------------+---------+------+------+----------+-----------------------------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------------------+------------+-------+----------------------+------------+---------+------+------+----------+-----------------------------------------------------------+
| 1 | SIMPLE | inventory_transactions | NULL | range | vendor_id,date | date | 4 | NULL | 1196 | 100.00 | Using where; Using index; Using temporary; Using filesort |
+----+-------------+------------------------+------------+-------+----------------------+------------+---------+------+------+----------+-----------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)