mysql新增外來鍵

2021-07-23 06:33:45 字數 3291 閱讀 9862

為已經新增好的資料表新增外來鍵:

語法:alter table 表名 add constraint fk_id foreign key(你的外來鍵欄位名) references 外表表名(對應的表的主鍵欄位名);

例: alter table tb_active add constraint fk_id foreign key(user_id) references tb_user(id)

//fk_id是外來鍵的名稱

/*

create table `tb_active` (

`id` int(11) not null auto_increment,

`title` varchar(100) character set utf8 collate utf8_unicode_ci not null,

`content` text character set utf8 collate utf8_unicode_ci not null,

`user_id` int(11) not null,

primary key (`id`),

key `user_id` (`user_id`),

key `user_id_2` (`user_id`),

constraint `fk_id` foreign key (`user_id`) references `tb_user` (`id`)

) engine=innodb default charset=latin1

*/

刪除外來鍵

語法: alter table table-name drop foreign key key-id;

例:   alter table `tb_active` drop foreign key `fk_id`

自動鍵更新和刪除:

外來鍵可以保證新插入的記錄的完整性,但是,如果在references從句中已命名的表刪除記錄會怎麼樣?在使用同樣的值作為外來鍵的輔助表中會發生什麼?

很明顯,那些記錄也應該被刪除,否則在資料庫中就會有很多無意義的孤立記錄,mysql可以通過向foreign key...references修飾符新增乙個ondelete或on update子句簡化任務,它告訴了資料庫在這種情況如何處理孤立任務

關鍵字     含義

cascade    刪除包含與已刪除鍵值有參照關係的所有記錄

set null   修改包含與已刪除鍵值有參照關係的所有記錄,使用null值替換(只能用於已標記為not null的字段)

restrict   拒絕刪除要求,直到使用刪除鍵值的輔助表被手工刪除,並且沒有參照時(這是預設設定,也是最安全的設定)

no action  啥也不做

請注意,通過on update 和 ondelete規則,設定mysql能夠實現自動操作時,如果鍵的關係沒有設定好,可能會導致嚴重的資料破壞,

例如:如果一系列的表通過外來鍵關係和ondeletecascade 規則連線時,任意乙個主表的變化都會導致甚至只和原始刪除有一些將要聯絡的記錄在沒有警告的情況被刪除,所以,我們在操作之前還要檢查這些規則的,操作之後還要再次檢查.

新增外來鍵

alter table locstock add foreign key locstock_ibfk2(stockid) references product(stockid)

locstock 為表名, locstock_ibfk2 為外鍵名 第乙個括號裡填寫外來鍵列名, product為表名,第二個括號裡是寫外來鍵關聯的列名

刪除外來鍵

alter table locstock drop foreign key locstock_ibfk2

檢視表有哪些外來鍵

show create table locstock

[constraint symbol] foreign key [id] (index_col_name, ...)

references tbl_name (index_col_name, ...)

[ondelete]

[on update ]

所有tables必須是innodb型 ,它們不能是臨時表。

·         在引用表中,必須有乙個索引,外來鍵列以同樣的順序被列在其中作為第一列。這樣乙個索引如果不存在,它必須在引用表裡被自動建立。

·         在引用表中,必須有乙個索引,被引用的列以同樣的順序被列在其中作為第一列。

·         不支援對外鍵列的索引字首。這樣的後果之一是blob和text列不被包括在乙個外來鍵中, 這是因為對這些列的索引必須總是包含乙個字首長度。

·         如果constraintsymbol 被給出,它在資料庫裡必須是唯一的。如果它沒有被給出,innodb自動建立這個名字。

mysql新增外來鍵

為已經新增好的資料表新增外來鍵 語法 alter table 表名 add constraint fk id foreign key 你的外來鍵欄位名 references 外表表名 對應的表的主鍵欄位名 例 alter table tb active add constraint fk id fo...

mysql新增外來鍵

為已經新增好的資料表新增外來鍵 語法 alter table 表名 add constraint fk id foreign key 你的外來鍵欄位名 references 外表表名 對應的表的主鍵欄位名 例 alter table tb active add constraint fk id fo...

MySQL新增外來鍵

為已經建立的資料表新增外來鍵 語法 alter table 表名 add constraint fk name 外來鍵名稱 foreign key 外來鍵欄位名 references 外表表名 對應的表的主鍵欄位名 例 alter table tb active add constraint fk ...