什么是外键

外键 将子表和父表建立关联

引入外键后,外键只能插入参照列表存在的值,参照列被参照的(即父表中被唯一约束的字段)值不能删除,保证了数据的完整性。举个列子,工地有包工头和小喽喽之分,你可以把小喽喽开除和招进,但不能把包工头给赶走,赶走包工头,小喽喽们就没钱回家过年,多可怜啊!所以说是不允许这样干的。

 

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;

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值