我有一个看起来相当简单的表结构,但是 MySQL 在一个简单的查询中默认为一个不太理想的 index_merge
。
表结构如下:
CREATE TABLE IF NOT EXISTS `event_log` (
`event_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(5) DEFAULT NULL,
`location_id` int(10) DEFAULT NULL,
`object_id` int(5) DEFAULT NULL,
`action_id` int(5) DEFAULT NULL,
`date_event` datetime DEFAULT NULL,
PRIMARY KEY (`event_id`),
KEY `user_id` (`user_id`),
KEY `date_event` (`date_event`),
KEY `action_id` (`action_id`),
KEY `object_id` (`object_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
解释基本的 SELECT 查询
EXPLAIN SELECT date_event
FROM event_log
WHERE user_id =123
AND object_id =456
AND location_id =789
返回这个:
select_type table type possible_keys key key_len ref rows Extra
SIMPLE event_log index_merge user_id,object_id object_id,user_id 5,5 NULL 27 Using intersect(object_id,user_id); Using where
为了便于阅读,这里有额外的一点:
Using intersect(object_id,user_id); Using where
为什么 MySQL 不在此查询中使用标准索引?为什么它与 user_id
和 object_id
相交?
最佳答案
查询最有效的索引是包含所有三个字段的复合索引,例如:(object_id, user_id, location_id)
。由于没有这样的索引,MySQL 会尽力从现有索引中获取大部分信息。
关于mysql - 为什么 MySQL 在此查询中显示 index_merge?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16283472/