SQL基础篇-多表查询

# 多表查询
-- 项目开发中,在进行数据库表结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本上分为三种:
-- 一对多
-- 多对多
-- 一对一
# 一对多(多对一)
# 案例: 部门 与 员工的关系
# 关系:一个部门对应多个员工,一个员工对应一个部门
# 实现:在多的一方建立外键,指向一的一方的主键
# 多对多
# 案例: 学生 与 课程的关系
# 关系:一个学生可以选修多门课程,一门课程也可以供多个学生选择实现:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键

-- 多对多
create table student(
    id int auto_increment primary key comment'主键ID',
    name varchar(10)comment'姓名',
    no varchar(10)comment'学号'
)comment'学生表';
insert into student values (null,'黛绮丝','1000010000'),(null,'谢逊','28160102'),(null,'般天正','2800108183'),(null,'韦一笑','2000020000');


create table course
(
    id   int auto_increment primary key comment '主键ID',
    name varchar(10) comment '课程名称'
)comment'课程表';
insert into course values (null, 'Java'), (null, 'PHP'),(null , 'MySQL'), (null, 'Hadoop');

create table student_course(
    id int auto_increment comment'主键'primary key,
    studentid int not null comment'学生ID',
    courseid int not null comment'课程ID' ,
    constraint fk_courseid foreign key(courseid) references course (id),
    constraint fk_studentid foreign key (studentid) references student (id)
)comment'学生课程中间表';
insert into student_course values (null,1,1),(null,1, 2),(null,1,3),(null,2,2),(null,2, 3),(null,3,4);

# 一对一
# 案例: 用户 与 用户详情的关系
# 关系: 一对一关系,多用于单表拆分,将一张表的基础字段放在一张表中,其他详情字段放在另一张表中,以提升操作效率
# 实现:在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一的(UNIOUE)


create table tb_user(
    id int auto_increment primary key comment'主键ID',
    name varchar(10)comment'姓名',
    age int comment'年龄',
    gender char(1)comment'1:男,2:女',
    phone char(11)comment '手机号'
)comment'用户基本信息表';

create table tb_user_edu
(
    id            int auto_increment primary key comment '主键ID',
    degree        varchar(20) comment '学历',
    major         varchar(50) comment '专业',
    primaryschool varchar(50) comment '小学',
    middleschool  varchar(50) comment '中学',
    university    varchar(50) comment '大学',
    userid        int unique comment '用户ID',
    constraint fk_userid foreign key (userid) references tb_user (id)
)comment'用户教育信息表';

insert into tb_user(id, name, age, gender, phone) values
                        (null,'黄渤',45,'1','18800001111'),
                        (null,'冰冰',35,'2','18800002222'),
                        (null,'码云',55,'1','18800008888'),
                        (null,'李彦宏',50,'1','18800009999');


insert into tb_user_edu(id, degree, major, primaryschool, middleschool, university, userid) values
    (null,'本科','舞蹈','静安区第一小学','静安区第一中学','北京舞蹈学院',1),
    (null,'硕士','表演','朝阳区第一小学','朝阳区第一中学','北京电影学院',2),
    (null,'本科','英语','杭州市第一小学','杭州市第一中学','杭州师范大学',3),
    (null,'本科','应用数学','阳泉第一小学','阳泉区第一中学','清华大学',4);


# 多表查询 -- 笛卡尔积
# 概述:指从多张表中查询数据
# 笛卡尔积:笛卡尔乘积是指在数学中,两个集合A集合 和 B集合的所有组合情况。(在多表查询时,需要消除无效的笛
# 卡尔积)
select * from emp,dept;
select * from emp,dept where dept_id =dept.id;
select * from emp  join dept d on emp.dept_id = d.id;

# 多表查询分类
# 连接查询
# 内连接:相当于查询A、B交集部分数据
# 外连接:
# 左外连接:查询左表所有数据,以及两张表交集部分数据
# 右外连接:查询右表所有数据,以及两张表交集部分数据
# 自连接:当前表与自身的连接查询,自连接必须使用表别名
# 子查询


-- ------ 内连接 --------
# 隐式内连接
# SELECT 字段列表 FROM 表1,表2 WHERE 条件.;
# 显式内连接
# SELECT 字段列表 FROM 表1[INNER]JOIN 表2 ON 连接条件 .;

# --内连接演示
# --1.查询每一个员工的姓名,及关联的部门的名称(隐式内连接实现)
# 表结构:emp ,dept
# 连接条件:emp.dept_id= dept.id

select emp.name,dept.name from emp,dept where emp.dept_id=dept.id;

select  e.name,d.name from emp e ,dept d where e.dept_id=d.id;
# 2.查询每一个员工的姓名,及关联的部门的名称(显式内连接实现)
select emp.name,d.name from emp  join dept d on emp.dept_id = d.id;

# 外连接查询语法:
# 左外连接
# SELECT 字段列表 FROM 表1 LEFT[OUTER]JOIN 表2 ON 条件
# 相当于查询表1(左表)的所有数据 包含 表1和表2交集部分的数据
# 右外连接
# SELECT 字段列表 FROM 表1 RIGHT[OUTER]JOIN 表2 ON 条件
# 相当于查询表2(右表)的所有数据 包含 表1和表2交集部分的数据

# 外连接演示
# 1.查询emp表的所有数据,和对应的部门信息(左外连接)
# 表结构:emp,dept
# 连接条件:emp.dept_id = dept.id
select *,d.name from emp left outer join dept d on d.id = emp.dept_id;
# 2.查询dept表的所有数据,和对应的员工信息(右外连接)
select e.*,d.* from emp e right join dept d on d.id = e.dept_id;
## 左右转换
select e.*,d.* from dept d left join emp e on d.id = e.dept_id;


# 连接查询-自连接
# 自连接查询语法:
# SELECT字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条件.;
# 自连接查询,可以是内连接查询,也可以是外连接查询


# 自连接
# 1.查询员工及其所属领导的名字
# 2.查询所有员工 emp 及其领导的名字emp ,如果员工没有领导,也需要查询出来

select e1.name as '员工',e2.name as '当前员工领导' from emp e1 left join emp e2 on e1.managerid=e2.id;
## 查询最底层的员工,小领导都不是
select e.员工 from
    (
    select e1.name as '员工',e2.name as '当前员工领导' from emp e1 left join emp e2 on e1.managerid=e2.id
    )  e
where e.员工
        not in
        (
        select distinct e2.name from emp e1 left join emp e2 on e1.managerid=e2.id where e2.name is not null
        )  ;

# 联合查询-union,union all
# 对于union查询,就是把多次查询的结果合并起来,形成一个新的查询结果集。
# SELECT字段列表 FROM 表 A..
# UNION [ALL]
# SELECT 字段列表 FROM 表B

# union all,union
# 1.将薪资低于 5000 的员工,和年龄大于 50 岁的员工全部查询出来.
## union all是直接合并  union是合并后并去重
select * from emp where salary<5000
union all
select * from emp where age>50;

select * from emp where salary<5000
union
select * from emp where age>50;


# 子查询
# 概念:SQL语句中嵌套SELECT语句,称为嵌套查询,又称子查询
# SELECT *FROM t1 WHERE column1=(SELECT column1 FROM t2);
# 子查询外部的语句可以是 INSERT/UPDATE/DELETE/SELECT的任何一个根据子查询结果不同,分为!
# 标量子查询(子查询结果为单个值)
# 列子查询(子查询结果为一列)
# 行子查询(子查询结果为一行)
# 表子查询(子查询结果为多行多列)
# 根据子查询位置,分为:WHERE之后、FROM之后、SELECT之后。

-- --标量子查询(子查询结果为单个值)-----
# ---标量子查询---
# --1.查询“销售部”的所有员工信息
select * from emp where dept_id = (select id from dept where dept.name='销售部');
# --2.查询在“方东自”入职之后的员工信息
select * from emp where entrydate>(select entrydate from emp where name='方东自');


-- -----列子查询 ------
# 子查询返回的结果是一列(可以是多行),这种子查询称为列子查询常用的操作符:IN、NOT IN、ANY、SOME、ALL
# IN              在指定的集合范围之内,多选一
# NOT IN          不在指定的集合范围之内
# ANY             子查询返回列表中,有任意一个满足即可
# SOME             与ANY等同,使用SOME的地方都可以使用
# ALL             子查询返回列表的所有值都必须满足
# -- 列子查询
# 市场部--1.查询“销售部”和'市场部'的所有员工信息
select * from emp where dept_id in (select id from dept where dept.name in ('销售部','市场部'));
# --2.查询比财务部所有人工资都高的员工信息
select * from emp where salary> ALL (select salary from emp where dept_id = (select id from dept where dept.name='财务部'));
select * from emp where salary> (select max(salary) from emp where dept_id = (select id from dept where dept.name='财务部'));
# --3.查询比研发部其中任意一人工资高的员工信息

select * from emp where salary> ANY (select salary from emp where dept_id = (select id from dept where dept.name='研发部'));


-- 行子查询
# 子查询返回的结果是一行(可以是多列),这种子查询称为行子查询常用的操作符:=、<>、IN、NOTIN
# --行子查询
# --1.查询与“张无忌”的薪资及直属领导相同的员工信息;
-- 查询张无忌的薪资和直属领导
select salary,managerid from emp where name='张无忌';

-- 与之相同的员工
select * from emp where (salary,managerid)=(select salary,managerid from emp where name='张无忌');

select * from emp where salary =(select salary from emp where name='张无忌') and managerid=(select managerid from emp where name='张无忌' );


# 表子查询
# 子查询返回的结果是多行多列,这种子查询称为表子查询
# 常用的操作符:IN

# 表子查询
# 查询与“鹿杖客”“宋远桥”的职位和薪资相同的员工信息
-- 查询与“鹿杖客”“宋远桥”的职位和薪资
select job,salary from emp where name in ('鹿杖客','宋远桥');
-- 相同的员工信息
select * from emp where (job,salary) in (select job,salary from emp where name in ('鹿杖客','宋远桥')) and name not in ('鹿杖客','宋远桥');
# 查询入职日期是“2004-01-01”之后的员工信息及其部门信息
select * from emp left join dept d on emp.dept_id = d.id where entrydate>'2004-01-01';

select e.*,d.* from(select * from emp where entrydate>'2004-01-01') e left join dept d on e.dept_id=d.id;


-- 题目练习 --
# 1.查询员工的姓名、年龄、职位、部门信息。
# 2.查询年龄小于30岁的员工姓名、年龄、职位、部门信息。
# 3.查询拥有员工的部门ID、部门名称。
# 4.查询所有年龄大于40岁的员工,及其归属的部门名称; 如果员工没有分配部门,也需要展示出来。
# 5.查询所有员工的工资等级。
# 6.查询"研发部"所有员工的信息及工资等级。
# 7.查询"研发部"员工的平均工资。
# 8.查询工资比"灭绝"高的员工信息
# 9.查询比平均薪资高的员工信息。
# 10.查询低于本部门平均工资的员工信息。
# 11.查询所有的部门信息,并统计部门的员工人数。
# 12.查询所有学生的选课情况,展示出学生名称,学号,课程名称

# 新增表 薪资等级表
create table salgrade(
    grade int,
    losal int,
    hisal int
)comment'薪资等级表';
insert into salgrade values(1,0,3000);
insert into salgrade values(2,3001,5000);
insert into salgrade values(3,5001,8000);
insert into salgrade values(4,8001,10000);
insert into salgrade values(5,10001,15000);
insert into salgrade values(6,15001,20000);
insert into salgrade values(7,20001,25000);
insert into salgrade values(8,25001,10000000);

-- # 1.查询员工的姓名、年龄、职位、部门信息。
select e.name,e.age,e.job,e.managerid,d.* from emp e left join dept d on e.dept_id = d.id;

-- 2.查询年龄小于30岁的员工姓名、年龄、职位、部门信息。
select e.name,e.age,e.job,e.managerid,d.* from emp e left join dept d on e.dept_id = d.id where age<30;

-- 3.查询拥有员工的部门ID、部门名称。
select emp.dept_id,d.name from emp left join dept d on emp.dept_id = d.id group by dept_id having count(emp.id)>0 and dept_id is not null;

-- 4.查询所有年龄大于40岁的员工,及其归属的部门名称; 如果员工没有分配部门,也需要展示出来。
select e.*,d.name from emp e left join dept d on e.dept_id = d.id where e.age>40;

-- 5.查询所有员工的工资等级。
select id,name,salary,
       case when salary>25000 then '8' when salary>20000 then '7' when salary>15000 then '6' when salary>10000 then '5'
        when salary> 8000 then '4' when salary>5000  then '3' when salary>3000 then '2' else '1' end as '员工工资等级'
from emp;

select e.name,s.grade from emp e,salgrade s where e.salary between  s.losal and s.hisal;

--  6.查询"研发部"所有员工的信息及工资等级。

select e.*,s.grade from emp e,salgrade s where e.dept_id=(select dept.id from dept where dept.name='研发部');

-- 7.查询"研发部"员工的平均工资。
select avg(e.salary) as '研发部员工平均工资' from emp e  where e.dept_id=(select dept.id from dept where dept.name='研发部');

-- 8.查询工资比"韦一笑"高的员工信息
select * from emp where salary>(select salary from emp where name='韦一笑');

-- 9.查询比平均薪资高的员工信息。
select * from emp where salary>(select AVG(salary)from emp);

-- 10.查询低于本部门平均工资的员工信息。
select  * from emp e ,(select dept_id,avg(salary)as '部门平均薪资' from emp where dept_id is not null group by dept_id ) a where e.dept_id=a.dept_id
and e.salary<a.部门平均薪资;

select  * from emp e left join (select dept_id,avg(salary)as '部门平均薪资' from emp where dept_id is not null group by dept_id ) a on e.dept_id=a.dept_id
where e.salary<a.部门平均薪资;

-- 11.查询所有的部门信息,并统计部门的员工人数。
select d.*,count(e.id)as'部门人数' from emp e right join dept d on e.dept_id = d.id group by d.id;

-- 12.查询所有学生的选课情况,展示出学生名称,学号,课程名称
select * from student st,student_course sc,course c where st.id=sc.studentid and sc.studentid=c.id;


select m.name,m.no,c.name  from (
              select st.*,sc.studentid,sc.courseid from student st left join student_course sc on st.id = sc.studentid
                  ) m left join course c  on m.courseid= c.id;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值