MySQL统计数据库所有表的数据量

x33g5p2x  于2021-12-30 转载在 Mysql  
字(1.6k)|赞(0)|评价(0)|浏览(330)

场景:mysql统计一个数据库里所有表的数据量,最近在做统计想查找一个数据库里基本所有的表数据量,数据量少的通过select count再加起来也是可以的,不过表的数据有点多,不可能一个一个地查

记得在Navicat里,选择一个数据量,点击表,如图:

是可以看到所有表具体的数据行的

然后可以通过sql实现?在mysql里是可以查询information_schema.tables这张表的

SELECT table_rows,table_name FROM information_schema.tables  
 WHERE TABLE_SCHEMA = '数据库名称' 
 and table_name not in ('不查询的表名称') 
 ORDER BY table_rows DESC;

要统计的,加上sum函数就可以

SELECT sum(table_rows) FROM information_schema.tables  
 WHERE TABLE_SCHEMA = '数据库名称' 
 and table_name not in ('不查询的表名称') 
 ORDER BY table_rows DESC;

OK,本来还以为已经没问题了,然后还是被反馈统计不对,后来去找了资料

https://dev.mysql.com/doc/refman/8.0/en/information-schema-tables-table.html
官网的解释:

  • 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 is NULL for INFORMATION_SCHEMA tables.
    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.)

大概意思是对于MyISAM才是正确的统计数据,但是对于InnoDB引擎的,可能与实际值相差 40% 到 50%,所以只是一个大概的统计

所以针对这种情况,要更改存储引擎,肯定是不太合适,因为InnoDB是默认的存储引擎,能支持事务外健,并发情况性能也比较好

所以,根据网上的做法,重新analyze 对应表,在mysql8.0版本是不管用的,发现查询数据还是不对,估计是mysql版本太高,mysql5版本没验证过

analyze table [table_name]

继续找资料,在Navicat工具->命令行页面,设置全局或者回话的information_schema_stats_expiry为0,表示自动更新,设置全局的不知道会不会影响性能,所以不知道还是设置会话的就可以

SET SESSION information_schema_stats_expiry=0;
SET @@SESSION.information_schema_stats_expiry=0;

查询设置的information_schema_stats_expiry值

show variables like '%information_schema_stats%';

MySQL 8.0为了提高information_schema的查询效率,会将视图tables和statistics里面的统计信息缓存起来,缓存过期时间由参数information_schema_stats_expiry决定

相关文章

微信公众号

最新文章

更多