MySQL基礎之數據管理【4】

外鍵約束的使用(只有InnoDB存儲引擎支持外鍵)

create table news_cate(
	id tinyint unsigned auto_increment key comment '編號',
	cateName varchar(50) not null unique comment '分類名稱',
	cateDesc varchar(100) not null default '' comment '分類描述'
)engine=innodb charset=utf8;

insert news_cate(cateName) values('國內新聞'),
('國際新聞'),
('娛樂新聞'),
('體育新聞');

create table news(
	id int unsigned auto_increment key comment '編號',
	title varchar(100) not null unique comment '新聞標題',
	content varchar(1000) not null comment '新聞內容',
	cateId tinyint not null comment '新聞所屬分類編號'
)engine=innodb charset=utf8;

insert news(title,content,cateId) values('a1','aaaa1',1),
('a2','aaaa2',1),
('a3','aaaa3',4),
('a4','aaaa4',2),
('a5','aaaa5',3);

將會產生髒數據的操作

delete from news_cate where id=2;
insert news(title,content,cateId) values('a6','aaaa6',45);

解決辦法:添加外鍵(保證數據的一致性和完整性)

--建表時指定外鍵([constraint 外鍵名稱] foreign key(外鍵字段名稱) references 主表(主鍵字段名稱))
--news中cateId的字段類型和約束條件要與主表news_cate中的id相似
--如果外鍵字段沒有創建索引,MySQL會自動幫我們添加索引
--子表的外鍵關聯的必須是父表的主鍵
create table news(
	id int unsigned auto_increment key comment '編號',
	title varchar(100) not null unique comment '新聞標題',
	content varchar(1000) not null comment '新聞內容',
	cateId tinyint unsigned not null comment '新聞所屬分類編號', 
	constraint cateId_fk_newsCate foreign key(cateId) references news_cate(id)
)engine=innodb charset=utf8;

insert news(title,content,cateId) values('a1','aaaa1',1),
('a2','aaaa2',1),
('a3','aaaa3',4),
('a4','aaaa4',2),
('a5','aaaa5',3);

--父表中的記錄有內容時(比如國內新聞裏有新聞就不能刪除國內新聞這個類別)不能進行以下操作(沒有外鍵約束的參照操作時)
--插入非法記錄
insert news(title,content,cateId) values('b1','bbbb1',8); --新聞類別裏沒有8,報錯
--顯示:有外鍵約束不能添加非法記錄
mysql> insert news(title,content,cateId) values('b1','bbbb1',8);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint 
fails (`king`.`news`, CONSTRAINT `news_ibfk_1` FOREIGN KEY (`cateId`) REFERENCES `news_cate` (`id`))

--刪除或更新父表中的記錄
delete from news_cate where id=1; --新聞類別1裏有記錄不能刪除,報錯
update news_cate set id=10 where id=1; --新聞類別1裏有記錄不能更新,報錯
--顯示:有外鍵約束不能刪除或更新父類記錄
mysql> delete from news_cate where id=1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint 
fails (`king`.`news`, CONSTRAINT `news_ibfk_1` FOREIGN KEY (`cateId`) REFERENCES `news_cate` (`id`))
--刪除子表之後才能刪出父表

動態創建外鍵及刪除外鍵操作

--動態添加外鍵
--動態添加外鍵之前表中的記錄一定是合法的記錄,沒有髒值,否則外鍵添加不成功
alter table tbl_name add [constraint 外鍵名稱] foreign key(外鍵字段名稱) references 主表(主鍵字段名稱); 

--動態刪除外鍵
alter table tbl_name drop foreign key fk_name;

--外鍵約束的參照操作
--cascade:從父表刪除或更新,子表也跟着刪除或更新,級聯的操作
--set null:從父表刪除或更新記錄,並設置子表的外鍵列爲null(要保證子表外鍵的字段可以爲null)
--not action|restrict:拒絕對父表做更新或刪除操作
alter table news
add foreign key(cateId) references news_cate(id)
on delete cascade on update cascade;
發佈了23 篇原創文章 · 獲贊 22 · 訪問量 3424
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章