外键的创建与修改

1.1.1
方法一:创建表的时候创建外键
语法:add
创建主表
create table stuinfo(
stuno int primary key,
stuname varchar(20) not null
);
创建从表
create table stuscore(
id int primary key ,
score int,
foreign key(id) references stuinfo(stuno)
)
方法二:修改表的时候创建外键
创建主表
create table stuinfo(
stuno int primary key,
stuname varchar(20) not null
);
创建从表
create table stuscore(
id int primary key ,
score int
)
更改表创建外键
创建外键的时候指定外键的名字
alter table stuscore add
constraint `FK1`
多学一招:要想给某个字段添加外键约束,改字段必须要存在索引才行。如果该字段存在索引,直接创建。如果没有,则MySQL会自动生成一个索引。
删除外键
语法:alter table 表名 drop
1.1 外键的操作
1、
2、
3、
创建主表
create table stuinfo(
stuno char(3) primary key,
stuname varchar(10));
创建从表
create table stumarks(
id int auto_increment primary key,
stuno char(3),
score int,
foreign key (stuno) references stuinfo(stuno) on delete set null on update cascade);
--主表删除的时候从表置空,主表更新的时候从表级联
测试
mysql> update stuinfo set stuno='aaa' where stuno='101';
mysql> delete from stuinfo where stuno='aaa';
脚下留心:只有innodb的引擎才支持主外键,myisam是不支持的。5.5的版本默认引擎是innodb的。