场景:

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决定

补充:查询表大小

我需要查询的库名为:kite

因此sql语句为:

select
table_schema as '数据库',
table_name as '表名',
table_rows as '记录数',
truncate(data_length/1024/1024, 2) as '数据容量(mb)',
truncate(index_length/1024/1024, 2) as '索引容量(mb)'
from information_schema.tables
where table_schema='kite'
order by table_rows desc, index_length desc;

结果如下:

总结 

到此这篇关于mysql如何统计一个数据库所有表数据量的文章就介绍到这了,更多相关mysql统计所有表数据量内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!