參照完整性通常通過外鍵(foreign key)的使用而被廣泛應用。長久以來,流行工具開源rdbms mysql并沒有支持外鍵,原因是這種支持將會降低rdbms的速度和性能。然而,由于很多用戶對參照完整性的優點倍感興趣,最近mysql的不同版本都通過新innodb列表引擎支持外鍵。由此,在數據庫組成的列表中保持參照完整性將變得非常簡單。
為了建立兩個mysql表之間的一個外鍵關系,必須滿足以下三種情況:
例子是理解以上要點的最好方法。如表a所示,建立兩個表,其中一個列出動物種類及相應的代碼(表名為:species),另一表列出動物園中的動物(表名為:zoo)。現在,我們想通過species關聯這兩個表,所以我們只需要接受和保存zoo表中包含species表中的合法動物的入口到數據庫中。
表a
注意:對于非innodb表, foreign key 語句將被忽略。mysql> create table species (id tinyint not null auto_increment, name varchar(50) not null, primary key(id)) engine=innodb;query ok, 0 rows affected (0.11 sec)mysql> insert into species values (1, 'orangutan'), (2, 'elephant'), (3, 'hippopotamus'), (4, 'yak');query ok, 4 rows affected (0.06 sec)records: 4 duplicates: 0 warnings: 0mysql> create table zoo (id int(4) not null, name varchar(50) not null, fk_species tinyint(4) not null, index (fk_species), foreign key (fk_species) references species (id), primary key(id)) engine=innodb;
現在,fieldszoo.species與species.id 之間存在一個外鍵關系。只有相應的zoo.specie與species.idfield的一個值相匹配,動物表中的入口才可被訪問。以下的輸出即演示了當你想輸入一個harry hippopotamus記錄,而使用到不合法的species代碼:
mysql> insert into zoo values (1, 'harry', 5);
error 1216 (23000): cannot add or update a child row: a foreign key constraint fails
這里,mysql核查species表以查看species代碼是否存在,如果發現不存在,就拒絕該記錄。當你輸入正確代碼的,可以與以上做比較。
mysql> insert into zoo values (1, 'harry', 3);
query ok, 1 row affected (0.06 sec)
這里,mysql核查species表以查看species代碼是否存在,當發現存在,允許記錄保存在zoo表中。
為了刪除一個外鍵關系,首先使用show create table找出innodb的內部標簽,如表b所示:
表 b
+-------+---------------------------------------------------+
| table | create table |
+-------+---------------------------------------------------+
| zoo | create table `zoo` (
`id` int(4) not null default '0',
`name` varchar(50) not null default '',
`fk_species` tinyint(4) not null default '0',
key `fk_species` (`fk_species`),
constraint `zoo_ibfk_1` foreign key (`fk_species`)
references `species` (`id`)
) engine=innodb default charset=latin1 |
+-------+----------------------------------------------------+
然后使用帶有drop foreign key 語句的alter table命令,如以下:
mysql> alter table zoo drop foreign key zoo_ibfk_1;
query ok, 1 row affected (0.11 sec)
records: 1 duplicates: 0 warnings: 0
為了將一個外鍵添加到一個現成的表中,使用add foreign key的 alter table語句指定合適的域作為一個外鍵:
mysql> alter table zoo add foreign key (fk_species) references species (id);
query ok, 1 rows affected (0.11 sec)
records: 1 duplicates: 0 warnings: 0
如以上例子解釋的,外鍵在捉摸數據入口錯誤上起著重要的作用,由此可建立更為強健更加集成的數據庫。另一方面值得提到的是,執行外鍵核實是內部資料處理的過程,且不同表之間指定復雜的內部關系可以導致數據庫的性能下降。所以,在參照完整性與性能考慮之間找到平衡點相當重要,而使用外鍵就是能夠確保性能與穩健之間的最優結合。
我期望本期的有關外鍵的介紹對你有所好處,你將會在下回的mysql數據庫設計中感受到外鍵的好處。編程快樂!
新聞熱點
疑難解答