我有一个简单的问题
SELECT userId, COUNT(*) AS c
FROM my_table
WHERE someId = 11 AND userId != 0
GROUP BY userId
ORDER BY c DESC
LIMIT 0, 5;
我在userId
和someId
上都有索引,但是在这两种情况下,查询在具有1M行的表上花费了2,5秒.
解释输出提供了以下信息:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE my_table ref userId,someId someId 4 const 6895 Using where; Using temporary; Using filesort
我也曾try 在(someId, userId)
或(userId, someId)
上创建两列索引,但速度也是一样的.
结果为SHOW CREATE TABLE my_table
,删除了其他未使用的列
CREATE TABLE `my_table` (
`userId` int(11) NOT NULL DEFAULT 0,
`someId` int(11) NOT NULL,
#some other unused colums
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `someId` (`someId`),
KEY `userId` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=746173
SHOW TABLE STATUS WHERE name LIKE 'my_table
人的结果
Name Engine Version Row_format Rows Avg_row_length Data_length Max_data_length Index_length Data_free Auto_increment Create_time Update_time Check_time Collation Checksum Create_options Comment Max_index_length Temporary
my_table InnoDB 10 Dynamic 728295 162 118079488 0 125009920 19922944 746173 2022-08-22 19:47:41 NULL NULL utf8_general_ci NULL 0 N