MYSQL外鍵(Foreign Key)的使用

來源:互聯網
上載者:User

標籤:war   應該   arc   定義   實現   表示   wol   dag   update   

轉載自:http://www.cppblog.com/wolf/articles/69089.html#Post

原文實在太精闢又形象,忍不住轉載過來留下筆記,像作者致敬

在MySQL 3.23.44版本後,InnoDB引擎類型的表支援了外鍵約束。
外鍵的使用條件:
1.兩個表必須是InnoDB表,MyISAM表暫時不支援外鍵(據說以後的版本有可能支援,但至少目前不支援);
2.外鍵列必須建立了索引,MySQL 4.1.2以後的版本在建立外鍵時會自動建立索引,但如果在較早的版本則需要顯示建立; 
3.外鍵關係的兩個表的列必須是資料類型相似,也就是可以相互轉換類型的列,比如int和tinyint可以,而int和char則不可以;

外鍵的好處:可以使得兩張表關聯,保證資料的一致性和實現一些級聯操作;

外鍵的定義文法:
[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...)
    REFERENCES tbl_name (index_col_name, ...)
    [ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]
    [ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]
該文法可以在 CREATE TABLE 和 ALTER TABLE 時使用,如果不指定CONSTRAINT symbol,MYSQL會自動產生一個名字。
ON DELETE、ON UPDATE表示事件觸發限制,可設參數:
RESTRICT(限制外表中的外鍵改動)
CASCADE(跟隨外鍵改動)
SET NULL(設空值)
SET DEFAULT(設預設值)
NO ACTION(無動作,預設的)

搞個例子,簡單示範一下使用,做dage和xiaodi兩個表,大哥表是主鍵,小弟表是外鍵:
建表:

 1  1 CREATE TABLE `dage` ( 2  2  `id` int(11) NOT NULL auto_increment, 3  3  `name` varchar(32) default ‘‘, 4  4  PRIMARY KEY  (`id`) 5  5) ENGINE=InnoDB DEFAULT CHARSET=latin1; 6  6 7  7CREATE TABLE `xiaodi` ( 8  8  `id` int(11) NOT NULL auto_increment, 9  9  `dage_id` int(11) default NULL,10 10  `name` varchar(32) default ‘‘,11 11  PRIMARY KEY  (`id`),12 12  KEY `dage_id` (`dage_id`),13 13  CONSTRAINT `xiaodi_ibfk_1` FOREIGN KEY (`dage_id`) REFERENCES `dage` (`id`)14 14) ENGINE=InnoDB DEFAULT CHARSET=latin1;

插入個大哥:

1 1mysql> insert into dage(name) values(‘銅鑼灣‘);2 2Query OK, 1 row affected (0.01 sec)3 3mysql> select * from dage;4 4+----+--------+5 5| id | name   |6 6+----+--------+7 7|  1 | 銅鑼灣 |8 8+----+--------+9 91 row in set (0.00 sec)

插入個小弟:

1 1mysql> insert into xiaodi(dage_id,name) values(1,‘銅鑼灣_小弟A‘);2 2Query OK, 1 row affected (0.02 sec)3 34 4mysql> select * from xiaodi;5 5+----+---------+--------------+6 6| id | dage_id | name         |7 7+----+---------+--------------+8 8|  1 |       1 | 銅鑼灣_小弟A |9 9+----+---------+--------------+

 

把大哥刪除:

1 1mysql> delete from dage where id=1;2 2ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`bstar/xiaodi`, CONSTRAINT `xiaodi_ibfk_1` FOREIGN KEY (`dage_id`) REFERENCES `dage` (`id`))

 


提示:不行呀,有約束的,大哥下面還有小弟,可不能扔下我們不管呀!

插入一個新的小弟:

1 1mysql> insert into xiaodi(dage_id,name) values(2,‘旺角_小弟A‘);              2 2ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`bstar/xiaodi`, CONSTRAINT `xiaodi_ibfk_1` FOREIGN KEY (`dage_id`) REFERENCES `dage` (`id`))3 

提示:小子,想造反呀!你還沒大哥呢!

把外鍵約束增加事件觸發限制:

 
 1 1mysql> show create table xiaodi; 2  2 3  3  CONSTRAINT `xiaodi_ibfk_1` FOREIGN KEY (`dage_id`) REFERENCES `dage` (`id`) 4  4 5  5mysql> alter table xiaodi drop foreign key xiaodi_ibfk_1;  6  6Query OK, 1 row affected (0.04 sec) 7  7Records: 1  Duplicates: 0  Warnings:  8  8mysql> alter table xiaodi add foreign key(dage_id) references dage(id) on delete cascade on update cascade; 9  9Query OK, 1 row affected (0.04 sec)10 10Records: 1  Duplicates: 0  Warnings: 0

再次試著把大哥刪了:

1 1mysql> delete from dage where id=1;2 2Query OK, 1 row affected (0.01 sec)3 34 4mysql> select * from dage;5 5Empty set (0.01 sec)6 67 7mysql> select * from xiaodi;8 8Empty set (0.00 sec)

得,這回對應的小弟也沒了,沒辦法,誰讓你跟我on delete cascade了呢!

例子說明的應該蠻清楚了吧,其他功能對應手冊自己實踐吧!:-)

 

MYSQL外鍵(Foreign Key)的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.