前情:问题来源
delete 操作:delete一条记录时,只是把记录位置或者数据页标记为“可复用”;磁盘的文件大小不会太大变化,不能回收表空间。
问题:
数据库有个表每天会进行大量的插入操作,之后会定期delete掉旧的数据,只留最新的数据,最近看了些文章,发现delete并不能清理表空间,需要对表进行重建,才能清理调被占用的空间。
一、查看数据库表空间
1.进入information_schema数据库
use information_schema;
2.查看所有数据大小
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables;
3.查看指定表大小
select concat(round(sum(DATA_LENGTH/1024/1024),2),'MB') as data from TABLES where table_schema='库名' and table_name='表名';
4.查看指定数据库的大小
select concat(round(sum(DATA_LENGTH/1024/1024),2),'MB') as data from TABLES where table_schema='库名';
5.查看所有表大小并排序
SELECT CONCAT(table_schema,'.',table_name) AS 'Table Name', CONCAT(ROUND(table_rows/1000000,4),'M') AS 'Number of Rows', CONCAT(ROUND(data_length/(1024*1024*1024),4),'G') AS 'Data Size',CONCAT(ROUND(index_length/(1024*1024*1024),4),'G') AS 'Index Size', CONCAT(ROUND((data_length+index_length)/(1024*1024*1024),4),'G') AS'Total'FROM information_schema.TABLES ORDER BY --total DESC;
二、找到空间占用大的表,重建并优化
1.重建表
alter table tablename ENGINE=InnoDB;
2.分析表
analyze table tablename;
3.优化表
optimize table tablename;