【发布时间】:2016-10-03 19:14:16
【问题描述】:
好的,我有以下 MySQL 表结构:
CREATE TABLE `creditlog` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`memberId` int(10) unsigned NOT NULL,
`quantity` decimal(10,2) unsigned DEFAULT NULL,
`timeAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`reference` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `memberId` (`memberId`),
KEY `timeAdded` (`timeAdded`));
我这样查询它:
SELECT SUM(quantity) FROM creditlog where timeAdded>'2016-09-01' AND timeAdded<'2016-10-01' AND memberId IN (3,6,8,9,11)
现在,我也使用use index (timeAdded),因为由于条目的数量,它更方便。解释上述查询显示:
type -> range,
key -> timeAdded,
rows -> 921294
extra -> using where
同时,如果我使用 memberId INDEX,它会显示:
type -> range,
key -> memberId,
rows -> 1707849
extra -> using where
现在,我的问题是有可能以某种方式将这两个索引组合在一起使用并减少查询的表面,因为我还需要添加更多条件(在其他列上)。
【问题讨论】:
-
是否要创建(timeAdded, memberId)的索引。
-
我有兴趣弄清楚实际的顺序
-
你测试了吗?
-
尝试以两种方式添加复合索引,(memberId,timeAdded) 和 (timeAdded,memberId)。两者似乎都改善了查询。不确定哪个表现更好。
-
检查基数对你有帮助