create table students( stu_num char(8) primary key, stu_name varchar(20) not null, stu_gender char(2) not null, stu_age int not null, cid int unique,#如果需要一对一关系,那么需要添加unique的约束。 constraint FK_STUDENTS_CLASSES foreign key(cid) references classes(class_id) #constraint(关键字) FK_STUDENTS_CLASSES(约束名称) foreign key(cid) (外键约束+具体字段) references classes(class_id)(关联的表的具体字段) constraint-约束 );
方式2:向创建表,在添加外键约束。
create table students( stu_num char(8) primary key, stu_name varchar(20) not null, stu_gender char(2) not null, stu_age int not null, cid int );
在创建表之后,为cid添加外键约束
修改学生表 添加约束 约束名称 外键约束(具体字段) 关联classes表的class_id列
alter table students add constriant FK_STUDENTS_CLASSES foreign key(cid) references classes(class_id);
删除外键约束
alter table students drop foreign key FK_STUDENTS_CLASSES;
向班级表添加班级信息
INSERT INTO CLASSES(CLASS_NAME,CLASS_REMARK) VALUES('Java2021','.....'); INSERT INTO CLASSES(CLASS_NAME,CLASS_REMARK) VALUES('Java2022','.....'); INSERT INTO CLASSES(CLASS_NAME,CLASS_REMARK) VALUES('Java2023','.....'); INSERT INTO CLASSES(CLASS_NAME,CLASS_REMARK) VALUES('Java2024','.....'); INSERT INTO CLASSES(CLASS_NAME,CLASS_REMARK) VALUES('C++2025','.....');
向学生表添加学生信息
insert into students(stu_num,stu_name,stu_gender,stu_age,cid) values('20220101','张三','男',20,1);#cid对应表classes中的class_id字段
insert into students(stu_num,stu_name,stu_gender,stu_age,cid) values('20220102','李四','女',19,2);#cid对应表classes中的class_id字段
insert into students(stu_num,stu_name,stu_gender,stu_age) values('20220103','王五','男',21);#cid可以为空
insert into students(stu_num,stu_name,stu_gender,stu_age,cid) values('20220104','赵六','女',22,3);#cid对应表classes中的class_id字段
外键约束-级联
当学生表中存在学生信息关联班级表中的某条记录时,就不能对班级表的这条记录进行修改ID和删除操作。
update classes set class_id=7 where class_name='Java2023'; #无法修改是因为关联了表students表的学员
update classes set class_id=8 where class_name='C++2025'; #未关联学生表中的学员
如果一定要修改班级表中的班级ID,该如何实现呢?
将引用班级的班级ID的学生记录中的cid修改为null
#第一步 取消词条数据的主外键关系,让外键ID值=NUL insert into students(stu_num,stu_name,stu_gender,stu_age,cid) values('20220104','赵六','女',22,3); #cid=NULL update students set cid=null where cid=3;
再修改班级信息表中班级表中的class_id
#第二步 修改班级信息class_id update classes set class_id=7 where class_name='Java2023';
将学生表中cid设置为null的记录的cid重新修改为班级对应的新class_id
#第三步 重新给学员信息关联班级信息 update students set cid=7 where stu_num=20220104;
使用级联操作来实现
在添加外键时,设置级联修改和级联删除
删除原有的外键
alter table students drop foreign key FK_STUDENTS_CLASSES;
重新添加外键,并设置级联修改和级联删除
alter table students add constraint FK_STUDENTS_CLASSES foreign key(cid) references classes(class_id) on update cascade on delete cascade; #on update cascade 修改级联 on delete cascade 删除级联 #重新添加外键约束,但是同时要设置级联的修改和删除【一荣俱荣一损俱损】