【发布时间】:2012-07-14 06:27:31
【问题描述】:
我有一个包含大约 3000 万条记录的表,我需要对其执行查询。根据我的阅读,我认为使用最左前缀和我需要选择的所有字段的复合索引是正确的方法,但是当我对查询运行解释时,它甚至没有使用索引。
这是查询:
select distinct email FROM my_table
WHERE `customer_id` IN(278,428,186,40,208,247,59,79,376,73,38,52,68,227)
AND `company_id` = 4
AND `active` = 1
AND `date` > '2012-04-15';
解释是这样的
+----+-------------+--------+-------+---------------+-------+---------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+-------+---------------+-------+---------+------+----------+-------------+
| 1 | SIMPLE | emails | index | customer_id | email | 772 | NULL | 29296705 | Using where |
+----+-------------+--------+-------+---------------+-------+---------+------+----------+-------------+
这些是字段
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL DEFAULT '',
`customer_id` int(10) unsigned DEFAULT NULL,
`company_id` int(10) unsigned NOT NULL,
`active` tinyint(1) unsigned NOT NULL DEFAULT '1',
`date` date DEFAULT NULL
索引看起来像这样
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`,`customer_id`),
KEY `customer_id` (`customer_id`,`company_id`,`active`,`date`)
我不太确定优化它的最佳方法是什么。
【问题讨论】:
-
@radashk 查询仅返回 3,117,636 行。在说明中,它显示有近 3000 万行需要过滤。
-
这些都是您使用 WHERE IN 子句的所有情况。它无法索引。
-
没有一种方法或最好的方法来提高性能,您必须采用不同的方法,直到找到最佳解决方案
标签: mysql select indexing key explain