mysql - 为什么 select count(*) from table_name 这么慢?

标签 mysql sql count

mysql> select count(*)
    -> from ip_address_varchar20;
+----------+
| count(*) |
+----------+
|  2764687 |
+----------+
1 row in set (1 min 28.80 sec)

我认为应该有一个字段来存储任何表的大小,但我发现 count(*) 太慢了。

为什么 DBMS 不对此进行优化?或者我在这方面做了一些不好的做法?

最佳答案

来自:https://wiki.postgresql.org/wiki/Why_PostgreSQL_Instead_of_MySQL:_Comparing_Reliability_and_Speed_in_2007

One operation that PostgreSQL is known to be slow performing is doing a full count of rows in a table, typically using this SQL:

SELECT COUNT(*) FROM table

The reason why this is slow is related to the MVCC implementation in PostgreSQL. The fact that multiple transactions can see different states of the data means that there can be no straightforward way for "COUNT(*)" to summarize data across the whole table; PostgreSQL must walk through all rows, in some sense. This normally results in a sequential scan reading information about every row in the table.

上面对 Postgres 的解释也适用于 MySQL 的 InnoDB。由于InnoDB使用MVCC。

有一些approaches使用 InnoDB 进行快速计数。例如,您可以使用估计,也可以使用触发器来维护表的行数。

关于mysql - 为什么 select count(*) from table_name 这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55507132/

相关文章:

python - 列表内容的长度,里面有列表

android - 选择 4 个网格位置之间的所有条目

php - 通过 mysql 数据库重定向多个 url?

mysql - 使用分组功能无效但没有GROUP BY

sql - 在创建SELECT查询以选择唯一行时需要帮助

MySQL - 如何按文本内容分组?

mysql - 空字符串插入零,而不是空值

mysql - 如何创建像搜索一样的 indeed.com?

sql - MySql中如何将一列的数据反转到另一列?

javascript - 简单的javascript击键计数