简体   繁体   中英

Why is mysql not using this index?

I have the following tables (some fields removed for conciseness):

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`)
) 

and

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`)
) 

When I run this query:

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 

I get this result:

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|

I'm puzzled by this. Why is the query using the hide_sitewide index? Why isn't it using the is_activity_comment index, especially when many of the fields in the where clause exist in the `is_activity_comment`` index?

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

begs for this composite index:

INDEX(is_spam, hide_statewide, is_activity_comment, date_recorded)

With the date last.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM