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;

猜你喜欢

转载自www.cnblogs.com/bigbox/p/12037233.html