【mysql磁盘碎片】MySql磁盘碎片
mysql当然也会产生磁盘碎片。
在查看表的status的时候,会显示出来这个信息:Data_free字段
Data_free
The number of allocated but unused bytes.
Beginning with MySQL 5.1.24, this information is also shown for InnoDB
tables (previously, it was in the Comment
value). InnoDB
tables report the free space of the tablespace to which the table belongs. For a table located in the shared tablespace, this is the free space of the shared tablespace. If you are using multiple tablespaces and the table has its own tablespace, the free space is for only that table. Free space means the number of completely free 1MB extents minus a safety margin. Even if free space displays as 0, it may be possible to insert rows as long as new extents need not be allocated.
For partitioned tables, this value is only an estimate and may not be absolutely correct. A more accurate method of obtaining this information in such cases is to query the INFORMATION_SCHEMA.PARTITIONS
table, as shown in this example:
SELECT SUM(DATA_FREE) FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA = 'mydb' AND TABLE_NAME = 'mytable';参考一下这篇文章
在插入数据之后进行删除【不要一次性全部删除,只删除一部分】,那么data_free字段会增加,而且随着删除条目越来越多,这个字段也越来越大。
然而在delete * from tb_name之后,data_free变为0了。mysql应该是在这里做了空间优化。
那么多次插入删除之后,这个空间就是浪费了。因为虽然给分配了空间,却没使用到。
此时,就需要优化了。
-------------------------------------------------------------------------------------------------
对于myisam引擎的表,可以使用optimize table tb_name来进行空间优化。
对于innodb引擎,可使用下列方法:
1、innodb 的optimize table 是映射到alter table的,做大innodb表优化前先drop掉所有的index,然后optimize 完了再rebuild index.速度要快很多。
2、对于使用独立表空间的innodb表,表比较小的可以ALTER TABLE table_name ENGINE = Innodb;表比较大的话,新创建一个表,把数据倒进去然后drop原来表。
-------------------------------------------------------------------------------------------------
ALTER TABLEtable_nameENGINE = Innodb;
这其实是一个NULL操作,表面上看什么也不做,实际上重新整理碎片了。当执行优化操作时,实际执行的是一个空的 ALTER 命令,但是这个命令也会起到优化的作用,它会重建整个表,删掉未使用的空白空间。
OPTIMIZE 可以整理数据文件,并重排索引。【据说仅针对myisam有效】