多表查询
前期工作建两张表:
create table dep(
id int,
name varchar(20)
);
create table emp(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);
insert into dep values
(200,'技术部'),
(201,'人力资源部'),
(202,'销售部'),
(203,'运营部');
insert into emp(name,sex,age,dep_id) values
('monicx','male',23,200),
('agekes','female',28,201),
('mege','male',38,201),
('joge','female',26,202),
('liuzhen','male',18,200),
('misli','female',18,204)
;
1 交叉连接:没有匹配任何条件,生成笛卡尔积
2 内连接:只连接匹配的行。
3左连接:在内连接的基础上,保留左边没有对应关系的记录
4 右连接:在内连接的基础上,保留右边没有对应关系的记录
![](https://i-blog.csdnimg.cn/blog_migrate/5c7dc6ce1b76d98ca6cc4599df7b6f4f.png)
4 全连接:在内连接的基础上,保留左、右边没有对应关系的记录
![](https://i-blog.csdnimg.cn/blog_migrate/ca58adef28bdcabf0bfc555364fe57dd.png)
子查询
把一个查询语句用括号括起来,当做另外一条查询语句的条件去用,称为子查询。
如:查询技术部员工的名字:
select name from emp where dep_id =
(select id from dep where name="技术部");
查询平均年龄在25岁以上的部门名
select name from dep where id in
(select dep_id from emp group by dep_id having avg(age) > 25);