MySQL表碎片整理
阿新 • • 發佈:2022-03-13
檢視指定資料庫所佔空間
select concat(round(sum(data_length / 1024 / 1024), 2), 'MB') as data from information_schema.tables where table_schema = 'dbName';
檢視指定表所佔空間
select concat(round(sum(data_length / 1024 / 1024), 2), 'MB') as data from information_schema.tables where table_schema = 'dbName' and table_name = 'tableName';
檢視指定資料庫下各個表分別佔用的空間
select concat(round(sum(data_length / 1024 / 1024), 2), 'MB') as data, table_name from information_schema.tables where table_schema = 'dbName' GROUP BY table_name ORDER BY data 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)' from information_schema.tables group by table_schema order by sum(data_length) desc, sum(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 order by data_length desc, index_length desc;
查看錶的碎片
select table_schema db_name, table_name, round(data_length / 1024 / 1024) as data_length_mb, round(index_length / 1024 / 1024) as index_length_mb, round(data_free / 1024 / 1024) as data_free_mb, engine from information_schema.tables where table_schema not in ('information_schema', 'mysql') and data_free > 0 order by data_free_mb desc;
其中:
·data_length:對於innodb表,表示實際分配給聚簇索引的空間大小
·data_free:對於innodb表,表示未使用的空間。對於分割槽表,這個值可能不準,具體要檢視information_schema.partitions
清除表碎片
方法1 alter table 表名 engine=InnoDB
alter table tableName engine=InnoDB;
方法2 optimize table 表名
#單個表 optimize table tableName; #多個表 optimize table tableName1,tableName2,tableName3,tableName4;
方法3:
#針對單個表 mysqlcheck -o dbName1 tableName1 -u root -pxxxx #針對某個庫 mysqlcheck -o dbName1 -u root -pxxxx #針對所有的庫 mysqlcheck -o --all-databases -u root -pxxxx