主键,唯一标示一个实体。是保证数据库的实体完整性,保证数据中数据的正确性和合理性,取值非空唯一。
外键,是用来使表与表之间联系。用来保证数据库的参照完整性,外键的取值必须来自参照表参照列的值,可以为空也可不为空。
以学生表,课程表和选课表为例:
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;//