按类别筛选时Mysql计数较慢


Mysql count slow when filter by category

为什么我的查询在运行时速度很快。

select count(*) as aggregate from `news` where `news`.`deleted_at` is null and `status` = '1'

但是,我跑得慢。

select count(*) as aggregate from `news` where `news`.`deleted_at` is null and `status` = '1' and `newscategory_id` = '17'

这是我的表news结构图,请看这里。

很抱歉,因为我的声誉低于8,所以我无法附上图片

尝试在用于选择的三列上添加一个复合索引:

ALTER TABLE news ADD INDEX comp_index (deleted_at, status, newscategory_id);

然后再次检查。可能会使用EXPLAIN来查看是否使用了您所拥有的任何索引。

索引用于快速查找具有特定列值的行。如果没有索引,MySQL必须从第一行开始,然后读取通过整个表查找相关行。越大表中,这项费用就越高。如果表中有列的索引有问题的是,MySQL可以快速确定要查找的位置数据文件的中间,而不必查看所有数据。这比按顺序读取每一行要快得多。

尝试将其添加到您的DB:中

CREATE INDEX newCategory_indx ON news (newscategory_id)
CREATE INDEX status_indx ON news (status)

与之前生成的(非索引列)结果相比,这将为您提供快速的结果。

要了解更多关于索引及其重要性的信息,请访问此处