简体   繁体   English

MySQL计数查询使用WHERE子句花费的时间太长

[英]MySQL count query takes too long with WHERE clause

I have a MySQL database, and I need to fetch the rows with COUNT. 我有一个MySQL数据库,我需要使用COUNT来获取行。

The database has around 20 million rows, and if I try the following 该数据库大约有2000万行,如果尝试以下操作

SELECT COUNT(id) FROM database_rows WHERE database_id = 53;

It takes about 5 minutes for it to fetch the COUNT. 大约需要5分钟才能获取 COUNT。

I believe the cause of the issue is the WHERE clause, but I need the where clause to count the rows that I want, not every single row in the table. 我相信问题的原因是WHERE子句,但我需要where子句来计算所需的行,而不是表中的每一行。

SELECT COUNT(id) FROM database_rows;

This query takes about 60ms to run. 该查询大约需要60毫秒才能运行。

I have looked helplessly at online articles, but they provided no sufficient solution. 我无奈地看了在线文章,但是他们没有提供足够的解决方案。

Is there any way I can optimise this query, and make it take only a few seconds? 有什么方法可以优化此查询并使它仅花费几秒钟?

Thank you. 谢谢。

An index on the database_id column might help here: database_id列上的索引可能在这里有所帮助:

CREATE INDEX idx ON database_rows (database_id);

This assumes that database_id does not already have some sort of index on it and that the value database_id = 53 would be a fairly infrequent occurrence. 这假定database_id尚无某种索引,并且值database_id = 53很少出现。 If either of these criteria be not true, then adding the index might not help. 如果这些条件之一都不成立,则添加索引可能无济于事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM