为什么mysql没有使用这个索引?

时间:2013-10-21 02:06:59

标签: mysql indexing explain

我有以下表格(为简洁起见,删除了一些字段):

CREATE TABLE `wp_bp_activity` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) NOT NULL,
  `type` varchar(75) NOT NULL,
  `is_activity_comment` tinyint(1) DEFAULT NULL,
  `hide_sitewide` tinyint(1) DEFAULT '0',
  `is_spam` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `type` (`type`),
  KEY `hide_sitewide` (`hide_sitewide`),
  KEY `is_spam` (`is_spam`),
  KEY `is_activity_comment` (`user_id`,`is_spam`,`hide_sitewide`,`is_activity_comment`)
) 

CREATE TABLE `wp_users` (
  `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_login` varchar(60) NOT NULL DEFAULT '',
  `user_pass` varchar(64) NOT NULL DEFAULT '',
  `display_name` varchar(250) NOT NULL DEFAULT '',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `user_login` (`user_login`),
  KEY `user_login_key` (`user_login`)
) 

当我运行此查询时:

EXPLAIN SELECT DISTINCT a . * , u.user_login, u.display_name
FROM wp_bp_activity a
LEFT JOIN wp_users u ON a.user_id = u.ID
WHERE a.is_spam =0
AND a.hide_sitewide =0
AND a.is_activity_comment =0
ORDER BY a.date_recorded DESC 

我得到了这个结果:

id|select_type|table|type  |possible_keys                            |key          |key_len|ref             |rows |Extra
1 |SIMPLE     |a    |ref   |hide_sitewide,is_spam,is_activity_comment|hide_sitewide|2      |const           |97718|Using where; Using temporary; Using filesort|
1 |SIMPLE     |u    |eq_ref|PRIMARY                                  |PRIMARY      |8      |dbname.a.user_id|1|

我对此感到困惑。为什么查询使用hide_sitewide索引?为什么不使用is_activity_comment索引,特别是当`is_activity_comment``索引中存在where子句中的许多字段时?

1 个答案:

答案 0 :(得分:0)

WHERE a.is_spam =0
AND a.hide_sitewide =0
AND a.is_activity_comment =0
ORDER BY a.date_recorded DESC 

请求这个综合指数:

INDEX(is_spam, hide_statewide, is_activity_comment, date_recorded)

最后一个日期。