子查询:查询语句中包含一个或者多个其他的查询语句,内部的查询语句称之为子查询
条件中使用
如果子查询的结果是多条记录(单列),作为条件使用时,应该用in或者not in
--查询各部门最高薪资的员工信息
select * from tb_emp
where salary in(
select max(salary)
from tb_emp
group by dept_id
);
如果子查询的结果时单个,可以使用= , > ,< ,>=,<=,!=
连接中使用
join
创建视图
视图:是一种查询语句,用于复杂sql语句的封装。
create view 视图名 as select语句
create view v_all_emp as select a.*,b.name department ,b.tel dept_tel
from tb_emp a
join tb_dept b on (a.dept_id=b.id);
–查询 练习电话未002的部门下的所有员工
select * from v all emp where dept_tel =‘002’;
删除视图:
drop view 视图名;
查询视图:
select table_nam ,table _type
from information_schema.tables
where table_schema=‘pdb’
and table_type=‘VIEW’;
创建表使用
create table tb_emp2
select * from tb_emp1;
create table tb_tb_emp3 select * from tb_emp where id=null;
插入数据使用
insert into 表名
子查询语句;
将tb_emp表中第一个部门的员工插入到tb_emp3表中
insert into tb_emp3
select * from tb_emp where dept_id=1
联合查询
子查询1
union[all]
子查询2
【
union【all】
…
】