5 多表查询和子查询
目录:
-
多表查询两种方法
1.连表操作
-
2.子查询
-
可视化软件
通过鼠标点点点完成数据库的增删改
-
多表查询练习题
-
#建表
create table dep(
id int primary key auto_increment,
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
('jason','male',18,200),
('tony','female',48,201),
('kevin','male',18,201),
('nick','male',28,202),
('owen','male',18,203),
('jerry','female',18,204);
先将查询涉及到的表拼接成一张大表 之后基于单表查询
(2)、笛卡尔积
select * from emp,dep;
select * from emp,dep where dep_id=id;
select emp.name,dep.name from emp,dep where emp.dep_id=dep.id;
涉及到多表操作的时候 为了避免表字段重复,需要在字段名的前面加上表名限制
上述操作并不是合理的连表操作,(jason所有的部门,只有一个值是我们想要的结果)
1.1.内连接
inner join 内连接:只连接两表中都存在(有对应关系)的数据
select * from emp inner join dep on emp.dep_id = dep.id;
1.2.左连接
left join 左连接:以左表为基准展示左表所有的数据没有对应则NULL填充
select * from emp left join dep on emp.dep_id = dep.id;
1.3.右连接
right join 右连接:以右表为基准展示右表所有的数据没有对应则NULL填充
select * from emp right join dep on emp.dep_id = dep.id;
1.4.全连接
union 全连接:展示左右两表中所有的数据没有对应则NULL填充
select * from emp left join dep on emp.dep_id = dep.id
union
select * from emp right join dep on emp.dep_id = dep.id;
2.
将一张表的查询结果当做另外一条SQL语句的查询条件
查询部门是技术或者人力资源的员工信息
1.先查询技术和人力资源的部门编号
select id from dep where name in ('技术','人力资源');
2.根据部门编号去员工表中筛选出对应的员工数据
select * from emp where dep_id in (200,201);
子查询:将SQL语句括号括起来即可充当查询条件
select * from emp where dep_id in (select id from dep where name in ('技术','人力资源'));