以下是 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;
以上方法结合系统表查询与配置优化,可有效管理和监控数据库空间。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。