MySQL(2)-关联映射

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值