在工作中会经常对数据库进行运维操作,例如大表清理等等
统计数据库占用的空间
统计同一个实例下面的所有数据库的容量大小
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_FREE/1024/1024, 2)) as '碎片占用(MB)'
from information_schema.tables
group by table_schema
order by sum(data_length) desc, sum(index_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_FREE/1024/1024, 2)) as '碎片占用(MB)'
from information_schema.tables
where table_schema='kalacloud_test_data';
统计数据库中表占用的空间
统计同一个实例下面的所有表的容量大小
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
order by data_length desc, index_length desc;
统计指定数据库各表的容量大小
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='kalacloud_test_data'
order by data_length desc, index_length desc;
找出碎片比较多的表
##data_free 单位是M
SELECT table_schema, TABLE_NAME, (data_free/1024/1024) as data_free FROM `information_schema`.tables
WHERE data_free > 3 * 1024 * 1024 AND ENGINE = 'innodb'
ORDER BY data_free DESC;
##根据排序已经实际情况优化碎片空间(innodb 不能使用optimize优化,如果不生效也可以用optimize table 或者 analyze table 看看)
alter table table_name engine='innodb';
##根据经验总结先执行 alter 在执行 optimize 好像比较见效果
不错
回复 @ apanly: 非常不错