外键的创建使得两张数据表产生关联,通过外键关系,可以检索到表1外键指向对应的表2的记录。
表1的外键可以指向表2的主键或者unique列。
一、创建数据表时添加外键关联
1. 创建班级数据表
create table Class(
Id int not null auto_increment,
No int not null,
Name varchar(50) default '',
primary key (Id),
unique(No)
);
- No: 班级号,作为Student的外键所关联的键,必须是unique或者primary的,否则会出现“ERROR 1215 (HY000): Cannot add foreign key constraint”
2. 创建学生数据表
create table Student(
Id int not null auto_increment,
Name varchar(50),
ClassNo int not null,
primary key (Id),
foreign key (ClassNo) references Class(No)
);
- ClassNo: 关联Class表的No列
二、重命名/删除数据表的外键
1. 重命名
alter table student
add constraint fk_student_classno
foreign key (classno) references class (no);
2. 删除
alter table student
drop foreign key fk_student_classno;