以下是 mysql 数据库空间大小查询与管理的常用方法,基于最新实践整理:
一、查询数据库空间大小
1. 查看所有数据库空间
select table_schema as '数据库', sum(table_rows) as '记录数', sum(truncate(data_length/1024/1024,2)) as '数据容量(mb)', sum(truncate(index_length/1024/1024,2)) as '索引容量(mb)', sum(truncate((data_length+index_length)/1024/1024,2)) as '总大小(mb)' from information_schema.tables group by table_schema order by sum(data_length) desc;
此语句统计所有数据库的总数据量、索引量及碎片空间,结果按数据容量降序排列。
使用
select table_schema as '数据库', sum(table_rows) as '记录数', sum(truncate(data_length/1024/1024,2)) as '数据容量(mb)', sum(truncate(index_length/1024/1024,2)) as '索引容量(mb)', sum(truncate((data_length+index_length)/1024/1024,2)) as '总大小(mb)' from information_schema.tables where table_schema='sftzhzx_jy-241220' group by table_schema order by sum(data_length) desc; select table_schema as '数据库', sum(table_rows) as '记录数', sum(truncate(data_length/1024/1024,2)) as '数据容量(mb)', sum(truncate(index_length/1024/1024,2)) as '索引容量(mb)', sum(truncate((data_length+index_length)/1024/1024,2)) as '总大小(mb)' from information_schema.tables where table_schema='sftzhzx_jd' group by table_schema order by sum(data_length) desc;
2. 查看指定数据库空间
select table_schema as '数据库', sum(data_length + index_length)/1024/1024 as '总大小(mb)' from information_schema.tables where table_schema = 'your_database_name' group by table_schema;
替换 your_database_name 后,可获取特定数据库的总空间占用。
使用
select table_schema as '数据库', sum(data_length + index_length)/1024/1024 as '总大小(mb)' from information_schema.tables where table_schema = 'sftzhzx_jy-241220' group by table_schema; select table_schema as '数据库', sum(data_length + index_length)/1024/1024 as '总大小(mb)' from information_schema.tables where table_schema = 'sftzhzx_jd' group by table_schema;
二、查询表级空间占用
1. 查看数据库中所有表空间
select table_name as '表名', truncate(data_length/1024/1024,2) as '数据容量(mb)', truncate(index_length/1024/1024,2) as '索引容量(mb)', truncate((data_length+index_length)/1024/1024,2) as '总大小(mb)' from information_schema.tables where table_schema = 'your_database_name' order by (data_length + index_length) desc;
用于分析指定数据库内各表的空间分布,识别大表。
2. 精确查询单表空间
select table_name as '表名', truncate((data_length + index_length)/1024/1024,2) as '总大小(mb)' from information_schema.tables where table_schema = 'your_database_name' and table_name = 'your_table_name';
适用于定位具体表的空间占用情况。
三、空间管理建议
1、自动扩展配置
在 my.cnf 配置文件中设置自动扩展参数,避免空间不足:
[mysqld] innodb_data_file_path = ibdata1:10m:autoextend
2、独立表空间优化
启用独立表空间可提升管理灵活性:
set global innodb_file_per_table = 1;
3、定期清理碎片
对频繁更新的表执行优化命令:
optimize table your_table_name;
以上方法结合系统表查询与配置优化,可有效管理和监控数据库空间。
到此这篇关于mysql 数据库空间使用大小查询的方法实现的文章就介绍到这了,更多相关mysql 空间使用大小查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论