外鍵約束的使用(只有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);
解決辦法:添加外鍵(保證數據的一致性和完整性)
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);
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;
update news_cate set id=10 where id=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;
alter table news
add foreign key(cateId) references news_cate(id)
on delete cascade on update cascade;