我有一个简单的问题

SELECT userId, COUNT(*) AS c 
FROM my_table 
WHERE someId = 11 AND userId != 0 
GROUP BY userId 
ORDER BY c DESC 
LIMIT 0, 5; 

我在userIdsomeId上都有索引,但是在这两种情况下,查询在具有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

推荐答案

需要考虑的建议,

ALTER TABLE my_table ADD INDEX my_table_ndx_someid_userid (someid, userid);

用于覆盖索引.

Change in the query, WHERE someid = 11 AND userid != 0
to WHERE someid = 11 AND userid > 0
for positive testing of value.

新的时间是什么时候?

Mysql相关问答推荐

如何计算超过特定数字的所有不同ID组,然后返回这些ID?

在 MySQL 中,如何对 LIKE 查询进行批量更新,删除字符?

MySQL Procedure 变量在 count(*) 上接收 null

检索按键列值分组的最新日期 (MySql)

使用 SET 变量进行 MySQL 查询

如何解决这个特定的 SQL 查询?我的解决方案还返回不想要的值

如何知道 Select 查询花费了多少时间?

巨大的未分区 MySQL 表问题

mySQL 中的主数据库和 IF 错误?

JOOQ:如何将 POJO 列序列化为 JSON

基于 2 列的重复行的 SQL 查询

mysql - 如何加入表中的动态列

查询以查找可用时隙

哪个更好 - 许多小桌子或一张大桌子?

在 PHP/MySQL 中将日期时间存储为 UTC

MySQL where NOT IN 名称数组?

MySQL:ALTER IGNORE TABLE 给出违反完整性约束

从 MySQL 中的日、月、年字段创建日期

更改 Laravel 的 created_at 和 updated_at 的名称

邮箱地址可接受的字段类型和大小?