mysql - select count(*) 查询太慢。我猜索引是行不通的

标签 mysql linux centos5 mysql5

我想请求评论,因为我做了更好的搜索。

我的服务器环境如下。

  • CentOS 版本 5.1
  • Linux 2.6,18
  • CPU:Intel (R) Xeon (R) CPU E3-1230 v3 @ 3.30GHz 8 核
  • 内存:8 GB
  • MySQL v5.5.40

此表 (kc_article-MyISAM) 中约有 260,000 条记录。

 mysql> desc kc_article;

+ --------------------- + ---------------------- + ---- -+ ----- + --------------------- + ---------------- +

| Field | Type | Null | Key | Default | Extra |

+ --------------------- + ---------------------- + ---- -+ ----- + --------------------- + ---------------- +

| idx | int (11) | NO | PRI | NULL | auto_increment |

| w_status | tinyint (4) | NO | MUL | 1 | |

| w_subj | varchar (255) | NO | MUL | NULL | |

~~ omission ~~

| w_section1 | int (11) | NO | MUL | NULL | |

| w_section2 | int (11) | NO | MUL | NULL | |

| w_theme | int (11) | NO | MUL | NULL | |

~~ Lay ~~

即使在查询条件中创建了索引,速度有时也会超过1、2、10、20秒。 w_status 和 w_section2 均已编入索引。

mysql> explain select count (*) as cnt from kc_article
       where w_status> 5
         and (w_section2 = '68')

+ ---- + ------------- + ------------ + ------ + ---------- ----------- + ------------ + --------- + ------- + ------- + ------------- +

| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |

+ ---- + ------------- + ------------ + ------ + ---------- ----------- + ------------ + --------- + ------- + ------- + ------------- +

| 1 | SIMPLE | kc_article | ref | w_section2, w_status | w_section2 | 4 | const | 33548 | Using where |

+ ---- + ------------- + ------------ + ------ + ---------- ----------- + ------------ + --------- + ------- + ------- + ------------- +

检查、恢复和优化表以及删除索引后重新创建表也是如此。 w_status的取值为0~6之间的整数,其中6为95%以上。

期待您的回复。

最佳答案

首先,这个查询:

select count (*) as cnt from kc_article where w_status> 5 and (w_section2 = '68')

应该写成:

select count (*) as cnt from kc_article where w_status =  and w_section2 = 68

括号是多余的,并且由于 w_section2 是一个整数,因此应该与整数而不是字符串进行比较。此外,w_status 的范围为 0 到 6,因此您可以使用相等条件而不是不等式。

您提到w_status 和 w_section2 都已编入索引。对于此查询,您需要在两列上建立复合索引,而不是在每列上建立索引(否则,MySQL 无法同时使用两者)。如果不存在,则创建它:

create index kc_article_status_section_idx on kc_article(w_status, w_section2);

几十万行并不是一个大数据集,我希望您的查询应该使用上述索引运行得很快。

关于mysql - select count(*) 查询太慢。我猜索引是行不通的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59421967/

相关文章:

MySQL InnoDB千表无法启动服务

mysql - 在 mysql 上创建触发器时,存储函数或触发器问题中​​不允许使用动态 SQL

linux - Shell - 在不包含子目录的目录中创建 zip 文件

php - 终端和 PHP 中的 PATH 不同

user-interface - 适用于 CentOS 的最佳 Mercurial (Hg) GUI?

c - OpenMPI 1.4.3 mpirun 主机文件错误

mysql - 时间窗口中每月计数(驱动器)的结果不正确

mysql - 如果 null 在 spring 数据 jpa 查询中返回空白

java - android 使用 java vs linux

node.js - Node.js 中的 ares_library_init 错误