加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

外键的创建与修改

(2016-04-22 11:11:32)

1.1.1 创建外键

方法一创建表的时候创建外键

语法add [constraint 外键名] foreign key (字段名) references 主表(公共字段)

创建主表

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` foreign key (id) references stuinfo(stuno)

多学一招:要想给某个字段添加外键约束,改字段必须要存在索引才行。如果该字段存在索引,直接创建。如果没有,则MySQL会自动生成一个索引。

 

删除外键

语法:alter table 表名 drop foreign key 外键的名字

 

1.1 外键的操作

 

1、 严格操作(前面讲的就是严格操作)

2、 置空操作(set null

3、 级联操作(cascade

创建主表

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的。

0

阅读 收藏 喜欢 打印举报/Report
前一篇:主表和从表
后一篇:聚合函数
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有