InnoDB 簡介 « 關於網路那些事...
MySQL 5.0 之後的版本支援的儲存引擎包括 MyISAM, InnoDB, MEMORY, CSV ...等
其中 InnoDB 屬於交易安全表(支援交易,行級鎖定,外來鍵和表加密)
MyISAM、MEMORY、CSV則屬於非交易安全表。
將目前支援的儲存引擎列出來,就能看到個引擎的支援狀況:
在 MySQL 5.5 之前,預設的儲存引擎是 MyISAM
MySQL 5.5 之後,預設搜尋引擎則設定為 InnoDB
如果要修改這個預設,可以直接修改 default-table-type
特性
InnoDB 儲存引擎具有交易安全的功能,因此具備了提交、回滾(rollback)以及崩壞修復能力,著重於安全性及功能面
因此,對於寫入速度相對於MyISAM 差一點,並且InnoDB在儲存資料時,會佔用較多的空間來管理資料及索引。
接下來介紹InnoDB 的一些特性:
AUTO INCREATMENT 欄位必須是索引
InnoDB 的 AUTO_INCREMENT 欄位必須符合以下條件
- 必須是索引 (INDEX or PRIMARY KEY)
- 若是組合索引,則必須是組合索引的第一列
可以設定外來鍵
InnoDB 是 MySQL 唯一支援外來鍵的儲存引擎
範例:
這裡透過國家及城市來說明外來鍵的用法
我們先建立好 country 及 city 的資料表
country
city
在 city 資料表中,設定外來鍵連結 FOREIGN KEY(country_id)
並且,設定了一些串聯式條件:
ON DELETE RESTRICT : 父表 counrty 具有存在 city 外來鍵時,無法單獨刪除 country 內容
ON UPDATE CASCADE : 父表 counrty 執行更新時,city 要同時更新
如果沒有指定ON DELETE 或ON UPDATE,NO ACTION 將會是預設值
插入幾筆資料
測試 ON DELETE RESTRICT
接下來測試看看,單獨刪除 country
因為有設定 ON DELETE RESTRICT,因此在具有子對應紀錄的情況,無法單獨刪除 country 資料
測試 ON UPDATE CASCADE
更新 country 的 id,再檢查 country 與 city 欄位值
因為有設定 ON UPDATE CASCADE,因此更新 country 資料也會同時更新子表單對應資料
暫時關閉外來鍵約束
有時需要暫時忽略外來鍵的束縛,直接操作時,可以透過下方的指令將外來鍵檢查關閉
若要重新啟用外來鍵檢查,則再將值設為1
範例:
直接刪除具有子對應紀錄的父層資料,會顯示錯誤
接著把 SET FOREIGN_KEY_CHECKS=0; 設定完成後
就能成功刪除父層資料
再重新開啟 SET FOREIGN_KEY_CHECKS=1; 外來鍵檢查功能
就恢復無法直接刪除具有子對應紀錄的父層資料
如果你喜歡我們的文章內容,請在這裡按個讚
Tweet