首页 > Mysql count(*)慢

Mysql count(*)慢

表结构
CREATE TABLE test (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(100) NOT NULL,
email varchar(100) NOT NULL,
password int(100) NOT NULL,
PRIMARY KEY (id),
KEY user_index (username,email),
KEY username_index (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
大概有500多W的数据量,select count(*) from test,花费时间有17s多,经过explain后Key使用了username_index索引,profile后发现其中的14s数据都浪费在sending data上,不知道该如何优化?


如果是MyISAM引擎,select count (*)会比较快,但也仅限于没有使用where语句的情况。
InnoDB的话,没什么好方法来优化select count (*)。前面同学提到的取大概值是个办法。总之,在速度,精确性和简单性这三者之间,你同时只能得到两者。
顺带说一个不相关的问题。username_index这个索引是多余的,因为它是user_index索引的前缀,可以去掉。


建议试试count(1)和count(id),这两个比count(*)的效率也许要高一些。
如果有效果的话,告诉我一下吧。
(我没在innodb上试过……)


这个查询慢的主要原因还是因为你使用的是innodb引擎,innodb的select(*)这样的查询要遍历一遍整个表,“sending data”这个状态实际上指读取存储上的数据。

根据 http://stackoverflow.com/questions/19267507/how-to-optimize-count-performance-on-innodb-by-using-index ,可以采取一个取巧的办法,就是从explain,show table status或者show index from 里面拿一个行数,这样会非常快且非常大约

【热门文章】
【热门文章】