mysql多列索引无法正常工作(如预期的那样)?

alp*_*hen 5 mysql indexing sql-order-by compound-index sql-execution-plan

我有一张这样的桌子

CREATE TABLE IF NOT EXISTS `tbl_folder` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `owner_userid` int(11) NOT NULL,
  `name` varchar(63) NOT NULL,
  `description` text NOT NULL,
  `visibility` tinyint(4) NOT NULL DEFAULT '2',
  `num_items` int(11) NOT NULL DEFAULT '0',
  `num_subscribers` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `owner_userid` (`owner_userid`),
  KEY `vis_sub_item` (`visibility`,`num_subscribers`,`num_items`)
) ENGINE=InnoDB
Run Code Online (Sandbox Code Playgroud)

因为我有一个可见性索引,num_subscribers和num_items,我希望只需要查看前15行,而EXPLAIN说55856行.任何的想法?谢谢

EXPLAIN SELECT t.id, name, description, owner_userid, num_items, num_subscribers
FROM  `tbl_folder`  `t` 
WHERE visibility =2
ORDER BY  `t`.`num_subscribers` DESC ,  `t`.`num_items` DESC 
LIMIT 15

id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE t ref vis_sub_item vis_sub_item 1 const 55856 Using where
Run Code Online (Sandbox Code Playgroud)

Rie*_*sio 2

您的 3 字段索引看起来不错并且EXPLAIN很有希望。

虽然它说“55856 行”,但这只是EXPLAIN.

因为key_len =1,您知道它使用复合索引的第一个字节作为相等/引用。

由于您的字段中没有提到文件排序Extra,因此您知道ORDER BY/sorting正在由索引处理。

如果您检查handler_%会话统计信息,您将更好地了解实际读取了多少行。

侧面想法:

因为您知道您最终将访问磁盘来检索行,所以如果 99% 的数据都已检索(只是推测),那么您可能会通过&visibility=2上的复合索引获得同样好/快的结果。或者如果您在 上有一个索引,则可以说同样好/快,具体取决于它的基数/唯一性。 num_subscribersnum_itemsnum_subscribers