MySQL中count(*)和information_schema.tables中的table_rows值不相同

前两天我还在高高兴兴地写了一篇文章《一条SQL查询出MySQL数据库中所有表的数据量大小》,心想这也太方便了,只用一条SQL就能统计出所有表的数据量,但没想到,最终还是翻车了。。。

翻车过程如下:

有一张表,在information_schema.tables中,其table_rows显示为1316万行,如图所示:
在这里插入图片描述
但是使用count(*)来查询该表的行数,结果居然为6055万行。
在这里插入图片描述
为什么两者不一致,且差距如此巨大呢?

翻车原因:
我们先来看一下官网的解释:

The TABLES table provides information about tables in databases.

information_schema.tables这张表提供数据库中表的一些信息;

TABLE_ROWS: The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40% to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.

table_rows这个字段,其值为行的个数。对于一些存储引擎,比如MyISAM,存储的是确切的行数。但是对于其他的存储引擎,比如InnoDB,这个值则是估算的,可能与实际值相差40%至50%。这种情况下应该使用COUNT(*)来获取准确的行数统计。

For InnoDB tables, the row count is only a rough estimate used in SQL optimization. (This is also true if the InnoDB table is partitioned.)

对于InnoDB表,行计数只是SQL优化中使用的粗略估计。(这也适用于 InnoDB 表进行了分区的情况。)

想要获取更多信息,可以参考MySQL官网中的The INFORMATION_SCHEMA TABLES Table

猜你喜欢

转载自blog.csdn.net/itigoitie/article/details/128161560