当前位置: 代码网 > it编程>数据库>Mysql > MySQL数据库实现统计所有表的空间占用与行数

MySQL数据库实现统计所有表的空间占用与行数

2026年02月09日 Mysql 我要评论
查看某个数据库中所有表的空间与行数统计select table_name as `表名`, table_rows as `行数`, round(data_length / 1024

查看某个数据库中所有表的空间与行数统计

select 
    table_name as `表名`,
    table_rows as `行数`,
    round(data_length / 1024 / 1024, 2) as `数据大小(mb)`,
    round(index_length / 1024 / 1024, 2) as `索引大小(mb)`,
    round((data_length + index_length) / 1024 / 1024, 2) as `总占用空间(mb)`,
    round((data_length + index_length) / 1024 / 1024 / 1024, 2) as `总占用空间(gb)`
from 
    information_schema.tables
where 
    table_schema = 'your_database_name' -- 替换为你的数据库名
order by 
    (data_length + index_length) desc;

执行结果

查看某个数据库总空间占用情况

select 
    table_schema as `数据库名`,
    sum(table_rows) as `总行数`,
    round(sum(data_length) / 1024 / 1024, 2) as `数据总大小(mb)`,
    round(sum(index_length) / 1024 / 1024, 2) as `索引总大小(mb)`,
    round(sum(data_length + index_length) / 1024 / 1024, 2) as `总占用空间(mb)`,
    round(sum(data_length + index_length) / 1024 / 1024 / 1024, 2) as `总占用空间(gb)`
from 
    information_schema.tables
where 
    table_schema = 'your_database_name'
group by 
    table_schema;

执行结果

知识扩展

统计数据库下所有表的数据行数

刚开始统计数据库中有多少行数据的时候,使用 information_schema.tables 去统计发现误差很大 ,具体原因这里不再说明

select
table_schema as '数据库',
table_name as '表名',
table_comment 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='test'
order by table_rows desc, index_length desc;

以下是另一个方法:

执行sql,生成所有表的统计语句

select concat(
'select "',
table_name,
'", count(*) as t from `',
table_schema,
'`.`',
table_name,
'` union all'
) from information_schema.tables

-- 排除指定库
where
 table_schema not in('mysql','information_schema','performance_schema','sys');

结果如下:

查询出来的结果拷贝出来,去掉最后一行的 union all

汇总

到此这篇关于mysql数据库实现统计所有表的空间占用与行数的文章就介绍到这了,更多相关mysql统计表空间占用与行数内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com