一、一对一
一张表的一条记录一定只能与另外一张表的一条记录进行对应,反之亦然。
有时候,为了业务,或者避免一张表中数据量过大,过复杂,在开发中会进行一对一方式来设计表。
二、 一对多(1方建主表(id为主键字段), 多方建外键字段)
一个实体的某个数据与另外一个实体的多个数据有关联关系, 一对多的关系在设计的时候,需要设计表的外键。
2.1. 班级表和学生表设计
部门表和员工表设计
image.png
2.2.创建数据库表
constraint 约束
foreign key就是表与表之间的某种约定的关系,由于这种关系的存在,能够让表与表之间的数据,更加的完整,关连性更强。
foreign key语句的式例:FOREIGN KEY(Sno) REFERENCES Student(Sno)
注意:表的外键必须是另一张表的主键
//创建班级表
create table class(id int primary key auto_increment,name varchar(20));
//创建学生表
create table student(id int primary key auto_increment,name varchar(20),sex varchar(20),class_id int,constraint foreign key(class_id) references class(id));
//插入班级数据
insert into class values(1,'ceshiban');
insert into class values(2,'kaifa');
//插入学生数据
insert into student values(1,'zhangsan','nan',1);
insert into student values(2,'lisi','nan',2);
insert into student values(3,'jingjing','nan',2);
//联查
select * from student where class_id=(select id from class where id=2);
补一个外键的注意(默认是约束): 删除主键信息时,当该主键字段值在外键表中存在时,该记录是不能删除的。---要把外键表是的相关信息删除之后,才能删除。
子查询:嵌套在其他查询中的查询。
4.3、多对多( 3个表= 2个实体表 + 1个关系表 )
一个实体的数据对应另外一个实体的多个数据,另外实体的数据也同样对应当前实体的多个数据。
一个学生可以有多个老师,一个老师可以教多个学生
解决方案:创建一个中间表,专门用来维护多表之间的对应关系,通常是能够唯一标识出数据的字段(主键)
create table teacher(id int primary key,name varchar(100));
create table student (id int primary key,name varchar(100));
create table teacher_student(teacher_id int,student_id int,constraint foreign key(teacher_id) references teacher(id),constraint foreign key(student_id) references student(id));
insert into teacher values(1,'梁老师');
insert into teacher values(2,'李老师');
insert into student values(1,”张三”);
insert into student values(2,”李四”);
insert into teacher_student values(1,1);
insert into teacher_student values(1,2);
insert into teacher_student values(2,1);
insert into teacher_student values(2,2);
//查询李老师所教的学生
select id from teacher where name=’李老师’
select student_id from teacher_student where teacher_id=id
select * from student where id in(select student_id from teacher_student where teacher_id =(select id from teacher where name='李老师'));
//查询张三的所有老师
select * from teacher where id in(select teacher_id from teacher_student where student_id=(select id from student where name='张三'));
五、 联表查询
分类:内连接、外连接、交叉连接
5.1. 初始定义表结构
create table customer(id int primary key auto_increment,name varchar(20),city varchar(20));
create table orders(id int primary key auto_increment,good_name varchar(20),price float(8,2),cus