外键的设置
方法一:在创建子表的时候,直接标明外键。
设置外键语法:
references 父表(主键);
constraint classno_FK foreign key (classno) references class(classno);
创建数据表
create table scores(
sid int(4) primary key auto_increment,
sname varchar(20),
sage int(3),
classno int(4),
constraint stu_classno foreign key(classno) references class(classno),
);
constraint 外键名字 foreign key (classno) references class(classno)
方法二:使用alter语句今天添加外键
alter table student add constraint stu_classno foreign key(classno) references class(classno);
alter table student add constraint stu_classno foreign key(classno) references class(classno) on delete cascade;
- 此时插入或者修改数据时,如果classno的值在student表中不存在则会报错
删除外键:
alter table student drop foreign key stu_classno;