1.多表的关系,一对一,一对多,多对多
2.实现关联的方法
- 一对一:在任意一方引入对方主键作为外键。
- 一对多:在“多”的一方,添加“一”的一方的主键作为外键。
- 多对多:产生中间关系表,引入两张表的主键作为外键,两个主键成为联合主键或使用新的字段作为主键。
3.以MySQL举例
- 一对一
创建country表:(主键是name)
create table country
{
name char(10) primary key,
language char(10)
};
创建presidengt表:(主键是name)
create table president
{
name char(10) primary key,
sex char,
f_country_name char(10) unique//注意:外键必须约束值唯一
};
对应关系:一个国家对应一个总统,一个总统对应一个国家。country表中的name对应president表中的f_country_name。指定字段f_country_name为外键,指向country表的主键country(name).
alter table president add constraint foreign key(f_country_name) references country(name);
测试:删除其中一个表的一条记录,另外一个表的记录也会消失
- 一对多
创建class表:(classname是主键)
create table class
{
classname char(10) primary key,
headteacher char(10)
};
创建stu表:(number是主键,f_classname是外键)
create table stu
{
number int primary auto_increment,
name char(10),
age int,
f_classname char(10)
};
对应关系:一个学生对应一个班,一个班对应多个学生。
alter table stu add constraint foreign key(f_classname) references class(classname);
测试:删除其中一个表的一条记录,另外一个表的记录也会消失
- 多对多
创建Teacher表:(teacher_no是主键)
create table teacher
{
teacher_no int primary key auto_increment,
name char(10)
};
创建stu表:(stu_no是主键)
create table stu
{
stu_no int primary key auto_increment,
name char(10)
};
创建中间表middle:
create table middle
{
id in primary key auto_increment,
f_teacher_no int,
f_stu_no int
};
对应关系:一个老师有多个学生,一个学生有多个老师。
alter table middle add constraint foreign key(f_teacher_no) references teacher(teacher_no);
alter table middle add constraint foreign key(f_stu_no) references stu(stu_no);