外键 将子表和父表建立关联
引入外键后,外键只能插入参照列表存在的值,参照列被参照的(即父表中被唯一约束的字段)值不能删除,保证了数据的完整性。举个列子,工地有包工头和小喽喽之分,你可以把小喽喽开除和招进,但不能把包工头给赶走,赶走包工头,小喽喽们就没钱回家过年,多可怜啊!所以说是不允许这样干的。
Create database chapter05;
Use chapter05;
Create table grade(
Id int(4) not null primary key,
Name varchar(36)
);
Create table student(
Sid int(4) not null primary key,
Sname varchar(36),
Gid int(4) not null
//或在建表的同时创建外键foreign key (gid) references grade (id);
);
将上述的两个表关联起来,添加外键约束
Alter table 表名 add constraint Fk_ID foreign key (外键字段名) references 外表表名 (主键字段名)
Alter table student add constraint FK_ID foreign key (gid) references grade (id);
Gid:为student表的外键
FK_ID:为外键名
删除外键约束
Alter table 表名 drop foreign key 外键名;
Alter table student drop foreign key FK_ID;