MySQL学习笔记------多表查询
目录
多表关系
一对多
多对多
一对一
多表查询
概述
分类
内连接(交集)
隐式内连接
显式内连接
编辑
外连接(from后为左表,join后为右表)
左外连接
右外连接
自连接
联合查询(union,union all)
子查询
分类
标量子查询
列子查询
行子查询
表子查询
多表关系
概述
项目开发中,在进行数据库表结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在各种联系
基本分为三类:一对多,多对多,一对一
一对多
典型案例:部门与员工
实现:在多的一方建立一个外键,指向一的一方的主键
多对多
典型案例:学生与课程的关系
实现:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键
#建立学生表
create table student(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '姓名',
no varchar(10) comment '学号'
)comment '学生表';
insert into student(id, name, no) VALUES (1,'孔明','1000000000'),(2,'士元','1000000001'),(3,'仲达','1000000003'),(4,',孟德','1000000004');
#建立课程表
create table course(
id int auto_increment primary key comment '主键ID',
name varchar(10) comment '课程名称'
)comment '课程表';
insert into course(id, name) VALUES (1,'Java'),(2,'MySQL'),(3,'PHP'),(4,'C++');
#建立学生课程表
create table student_course(
id int auto_increment primary key comment '主键',
student_id int not null comment '学生ID',
course_id int not null comment '课程编码',
constraint fk_courseid foreign key (course_id)references course(id),
constraint fk_student_id foreign key (student_id)references student(id)
)comment '学生课程中间表';
insert into student_course(id, student_id, course_id) VALUES (1,1,1),(2,2,2),(3,3,3),(4,4,4);
添加外键后出现蓝色小钥匙
一对一
案例:用户与用户详情
关系:一对一,用于单表拆分,将表的基础字段放在一张表中,其他详情字段放到另一张表中,提高操作效率
实现:在任意一方加入外键,关联另一方的主键,并且设置外键为唯一的(unique)
多表查询
概述
建表
create table dept(
id int auto_increment comment 'ID' primary key ,
name varchar(50) not null comment '部门名称'
)comment '部门表';
insert into dept(id,name) VALUES (1,'研发部'),(2,'市场部'),(3,'财务部'),(4,'销售部'),(5,'总经办'),(6,'人事部');
create table employee(
#唯一标识,主键,自动增长为auto_increment
id int primary key auto_increment comment 'ID',
#不为空且唯一
name varchar(10) not null unique comment '姓名',
#大于零小于120
age int check ( age>0&&age20
union all
select *from employee where salary>20000;
去掉all可去重
注意事项:对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致
子查询
SQL语句中嵌套select语句,称为嵌套查询,又称子查询
语法:
select * from t1 where column1=(select co;lumn1 from t2);
子查询外部的语句可以是insert/update/delect/select的任何一个
分类
根据子查询结果不同可分为:
标量子查询(子查询结果为单个值)
列子查询(子查询结果为1列)
行子查询(子查询结果为1行)
表子查询(子查询结果为多行多列)
根据子查询位置分为:where之后、from之后、select之后。
标量子查询
子查询返回的结果是单个值(数字、日期、字符串等),最简单的形式
#标量子查询 select*from employee where dept_id=(select id from dept where name='财务部'); #()内返回值为销售部id
列子查询
#列子查询 select *from employee where dept_id in (select id from dept where name='财务部'or name='研发部'); #空格内返回一列
行子查询
#行子查询 select *from employee where (salary,manageid)=(select salary,manageid from employee where name='周瑜');
表子查询
#表子查询 select e.*,d.*from (select*from employee where entrydate>'2000-01-01') e left outer join dept d on e.dept_id=d.id;






