表关系管理
1、概述
表与表之间的关系可以是一对一、一对多、多对一的。通过外键把表连接起来,外键放在任意一张表都可以,通常选择由从表(相对次要的表)来持有外键(因为一旦删除数据,删除从表,外键也一并被删除,主表不会留下脏数据)。
课程表:
学生表:
选课表:
选课表:就是中间表。
表关系管理之多对多:通过中间表进行管理,中间表同时持有双方外键,中间表的主键是双方外键的联合主键。
创建【学生_课程】中间表
create table student_course(
sid integer not null,cid integer not null,
primary key (sid,cid)
);– 如果没有设置主键,可以通过修改表字段的方式来添加【联合主键】
– alter table student_course add constraint s_c primary key (sid,cid);
Create Table |
|
2、外键管理
2.1 定义外键
foreign key 从表名(classid) references 主表名(id)
create table s_orderform(
o_id int auto_increment primary key,
o_buyer_id int,
o_seller_id int,
o_totalprices double,
o_state varchar(50),
o_information varchar(200),
foreign key(o_buyer_id) references s_user(u_id), #外链到s_user表的u_id字段
foreign key(o_seller_id) references s_user(u_id) #外链到s_user表的u_id字段
)
2.2 追加外键
方法一:
ALTER TABLE student ADD CONSTRAINT FK_student_aclass
FOREIGN KEY student(classid) REFERENCES aclass(id);
方法二:
ALTER TABLE temp ADD FOREIGN KEY temp(cid) REFERENCES clazz(id);
2.3 删除外键
show create table student; --找出classid对应的外键名称
alter table student drop foreign key FK_student_aclass; 删除外键名称
alter table student drop classid;
这样定义外键使用起来不够灵活,不能够给外键设置默认值,外键中的值必须是主表中存在的。在实际应用中给从表设置一个键,直接用来当作外键使用,不用加外键(foreign key)修饰。
3、范例
以身份证idcard、学生student、班级clazz、课程course为例进行表关系管理。
表关系包括一对一、一对多、多对多。通过外键对表关系进行管理,外键放在哪张表中都可以,一般存在不是很重要的那张表中。
例如:
1、表idcard与student是一对一的关系,一个学生对应一个身份证。
create table idcard(
id int primary key auto_increment,
cardId varchar(20) unique,
foreign key(id) references student(id)
);
2、表student与clazz是一对多的关系,一个班级可以有多个学生
create table clazz(
id int primary key auto_increment,
cName varchar(20) unique not null,
cTeacherCharge varchar(20) null,
cNum int
);
create table student(
id int primary key auto_increment,
sName varchar(20) unique not null,
age int,
gender tinyint(1) default null,
enterTime datetime,
foreign key(id) references clazz(id)
);
3、表student与course是多对多的关系,一个学生可以选择多门课,一门课可以被多个学生选择
create table course(
id int primary key auto_increment,
name varchar(20) unique not null,
);
创建中间表student_course
create table student_course(
sid int not null,
cid int not null,
primary key(sid,cid)
);