您的位置:首頁技術文章
文章詳情頁

mysql增加了表格字段,結果表格數據體積減小了?

瀏覽:78日期:2022-06-15 17:28:55

問題描述

發現了兩個需要新存儲的字段,就通過alter add添加了兩個字段,一個int, 一個float,結果發現變更完之后表格占用的體積反而減少了。

變更前:43個字段,14個索引字段,8141516 kb;變更后:45個字段,14個索引字段,8120649 kb;數據表大約226w條數據,myisam引擎,新添加的兩個字段里面尚未寫入數據,但減少了大約20M。

是因為在做數據表變更時同時做了優化、壓縮之類的操作嗎?

問題解答

回答1:

alter table在大部分情況下,會對原來的表生成一個臨時的副本(臨時表)。然后更新會進行到這個臨時表里,創建一個新的表,刪除原來的表。所以可以通過alter table 來優化表空間,修復操作產生的碎片空間。所以表空間變小了。我描述的可能不是很好,官方文檔原話是這樣子的

In most cases, ALTER TABLE makes a temporary copy of the original table. MySQL waits for other operations that are modifying the table, then proceeds. It incorporates the alteration into the copy, deletes the original table, and renames the new one. While ALTER TABLE is executing, the original table is readable by other sessions (with the exception noted shortly). Updates and writes to the table that begin after the ALTER TABLE operation begins are stalled until the new table is ready, then are automatically redirected to the new table without any failed updates. The temporary copy of the original table is created in the database directory of the new table. This can differ from the database directory of the original table for ALTER TABLE operations that rename the table to a different database.

具體官方文檔鏈接可以參考https://dev.mysql.com/doc/ref...

PS: 可以看文檔下面的comments,有人說到

You can use Alter Table to optimise a table without locking outselects (only writes), by altering a column to be the same as it’scurrent definition. This is better than using repair table whichobtains a read/write lock.

截個圖

mysql增加了表格字段,結果表格數據體積減小了?

国产综合久久一区二区三区