select count(*)查询太慢。我想通过索引

问题描述 投票:0回答:3
无法正常工作

我想征求意见,因为我进行了更好的搜索。

我的服务器环境在下面。

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

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

 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%或更高。

我期待您的来信。

mysql linux centos5 mysql5
3个回答
1
投票

首先,此查询:

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

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


0
投票

从kc_article的cnt中选择计数(1),其中w_status> 5并且w_section2 ='68'


0
投票

此综合索引,按此顺序是您所需要的:

INDEX(w_secdion2, w_status)

建立索引时,start带有=子句。参见http://mysql.rjweb.org/doc.php/index_cookbook_mysql

© www.soinside.com 2019 - 2024. All rights reserved.