数据库主键和外键

主键,唯一标示一个实体。是保证数据库的实体完整性,保证数据中数据的正确性和合理性,取值非空唯一。

外键,是用来使表与表之间联系。用来保证数据库的参照完整性,外键的取值必须来自参照表参照列的值,可以为空也可不为空。

以学生表,课程表和选课表为例:

create database db003;
use db003;
create table Course(courseId int,teacherId int, primary key (courseId));
create table Student(studentId int,name char(10), primary key (studentId));
create table Choose(studentId int,courseId int, primary key (studentId, courseId),foreign key (studentId) references Student(studentId),foreign key (courseId) references Course(courseId));

alter table Student add mobile int;
alter table Student add age int not null;

insert Course values (001,1001);//ok
insert Course values (001,1002);//错误,不能插入重复键
insert Course values (002,1003);//ok
insert Course values (003,null);//ok

insert Student values (2001,'xiaohong',18888,24);//ok
insert Student values (2002,'xiaowei',1880988,24);//ok

insert Choose values (2001,001);//ok
insert Choose values (2001,002);//ok
insert Choose values (2001,004);//Course表中并没有004的课程

update Course set teacherId=1005 where courseId=001;
update Student set name='xiaoming' where studentId=2002;


delete from Choose where courseId=001 and studentId=2001;
delete from Course where courseId=001;//如果这行先执行,无法成功,因为外键约束的存在性限制

drop table Student;//如果首先是删除Student的话,无法成功,因为有外键约束
drop table Choose;//



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值