MySQL的多表联查和嵌套查询

1.数据准备

### 创建表与插入数据准备

```python
#建表
create table dep2(
id int,
name varchar(20) 
);

create table emp2(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);

#插入数据
insert into dep2 values
(200,'技术'),
(201,'人力资源'),
(202,'销售'),
(203,'运营');

insert into emp2(name,sex,age,dep_id) values
('tank','male',17,200),
('egon','female',48,201),
('kevin','male',38,201),
('jason','female',28,202),
('owen','male',18,200),
('sean','female',18,204);

# PS: 昨天讲了如何根据表关系对字段进行拆分,目的是为了更好的管理,表数据都存放在硬盘中,存不是目的,目的是为了取,所以我们将数据从硬盘读到内存中,接下来我们因应该将他们拼成一张表来查询更加合理;

# 注意: 将拆分的表,再拼接到一起进行查询, 可以通过一张表查另一张表的数据;
```



### 1、关联查询

```mysql
# 左表的一条记录与右表的一条记录都对应一遍称之为 --> "笛卡尔积"   PS: 百度科普
# 将所有的数据都对应了一遍,虽然不合理但是其中有合理的数据,现在我们需要做的就是找出合理的数据
View Code

2. 联表查询和子查询

1、inner join
# 1、内连接:只取两张表有对应关系的记录
select * from emp2 inner join dep2 on emp2.dep_id = dep2.id;
select * from emp2 inner join dep2 on emp2.dep_id = dep2.id and dep2.name = '技术';

2、left join
# 2、左连接: 在内连接的基础上保留左表没有对应关系的记录
select * from emp2 left join dep2 on emp2.dep_id = dep2.id;

3、right join
# 3、右连接: 在内连接的基础上保留右表没有对应关系的记录
select * from emp2 right join dep2 on emp2.dep_id = dep2.id;

4、union
# 4、全连接:在内连接的基础上保留左、右面表没有对应关系的的记录
select * from emp2 left join dep2 on emp2.dep_id = dep2.id
union
select * from emp2 right join dep2 on emp2.dep_id = dep2.id;
```
### 2、子查询

```mysql
# 子查询就是将一个查询语句的结果用括号括起来,当做另一个查询语句的条件去用

# 1.查询部门是技术或者人力资源的员工信息
'''
先获取技术部和人力资源的id号,再去员工表里根据前面的id筛选出符合要求的员工信息;
'''
select * from emp2 where dep_id in (select id from dep2 where name='技术' or name='人力资源');


# 2.每个部门最新入职的员工 思路:先查每个部门最新入职的员工,再按部门对应上联表查询
# 查第一张emp表
select t1.id, t1.name, t1.hire_date, t1.post, t2.* from emp as t1 
inner join 
(select post, max(hire_date) as max_date from emp group by post) as t2 
on t1.post = t2.post
where t1.hire_date = t2.max_date;

3.三表联查的一些示例

SELECT
S.SName AS 姓名, CS.CourseName AS 课程, C.Score AS 成绩 FROM Students AS S # 注意:并不是from student下面所有的连表都直接和studnet 相连,比如四张表,五张表 INNER JOIN Score AS C ON S.SCode
= C.StudentID # stdent表先和score表 形成一个大表 INNER JOIN Course AS CS ON CS.CourseID = C.CourseID # 再用这张大表和课程表相连

4. 查询较为复杂时,一次写不出sql  可以分步来写

查询挂科超过两门(包括两门)的学生姓名和班级

select student.sname,class.cid,t.student_id from student 
inner join 
(select student_id,count(*) as count from score where num <60 group by student_id HAVING count > 1) as t on t.count = student.sid inner join class on student.class_id = class.cid
原文地址:https://www.cnblogs.com/bigbox/p/12037233.html