InnoDB 對 Primary Key 的選擇

前幾天 Ant 在「淺入淺出 MySQL & PostgreSQL」剛好有提到,結果 Percona 這兩天也丟出了這個題目,不過這邊討論的是空間的問題:「Illustrating Primary Key models in InnoDB and their impact on disk usage」。

一樣的作法,Primary Key 的選擇有三種:

  • INT + AUTO_INCREMENT
  • BINARY(16) (Ordered UUID)
  • CHAR(36) (Random UUID)

用的是 Jeremy Colespace-lsn-age-illustrate 畫出 LSN 的值 (InnoDB 的 Log Sequence Number,由於嚴格遞增,可以藉由這個值知道每個 page 最新被修改的時間):

I then used the powerful tool innodb_space’s function space-lsn-age-illustrate (from Jeremy Cole’s innodb_ruby project) to plot the LSN (InnoDB’s Log Sequence Number, an always-incrementing value) pages from each table that uses the different Primary Keys via ASCII colour (so hot, right? Thanks Jeremy!!).

測試是 INSERT-only 的 case,雖然不太能理解為什麼要用 CHAR(36) 存 UUID,而非與 BINARY(16),但可以看出一些 pattern。

有順序的 INT + AUTO_INCREMENT 與 BINARY(16) (Ordered UUID) 都可以看出層次 (一直往後寫),而且也看得出來 BINARY(16) 比 INT 大了不少:

而 CHAR(36) 當然是最大的,而且寫入的 i/o 也最隨機:

Leave a Reply

Your email address will not be published. Required fields are marked *