高级查询
1.多表查询(关联查询,连接查询)
- 内连接
- 没有主从表之分。
- 与连接顺序无关
- 内连接出现在结果集中的数据必须出现在每一个关联表中。
select * from emp,dept where emp.deptno = dept.deptno;
select * from emp inner join dept on emp.deptno = dept.deptno;
select * from emp inner join dept using (deptno); 不通用,必须通用列字段名称一样,会去除重复列。 |
- 外连接(左外连接 右外连接)
- 有主从表之分,与连接顺序有关。
- 以主表为基准,依次在从表中查找与主表记录相关联记录,如果找到则关联并显示,否则以null填充。
select * from emp left/right join dept on emp.deptno = dept.deptno; |
2.子查询(嵌套查询)
- 一次查询的结果作为另一查询的条件或者结果集,称为子查询。
子查询返回结果一条记录 select * from dept where deptno = (select deptno from emp where empno=7369);
子查询返回结果多条记录 select * from dept where deptno in ( select deptno from emp where sal > 2000); any/all =any: 相当于in >any:大于最小值 <any:小于最大值 <>all: 相当于not in >all:大于最大值 <all:小于最小值
# 查询超过所在部门的平均工资的员工信息。 #关联 select * from emp, (select deptno,avg(sal) avg from emp group by deptno) e where e.deptno = emp.deptno and sal > e.avg; #子查询 #1.主查询将deptno传给子查询 #2.子查询根据主查询传的部门编号查询该部门的平均工资 #3.子查询将结果返回给主查询,主查询执行。 select * from emp e1 where sal >( select avg(sal) avg from emp e2 where e2.deptno = e1.deptno);
#查询工资>2000的员工所在部门的名称 select dname from dept where deptno in (select deptno from emp where sal > 2000);
#exists select dname from dept where exists( select * from emp where sal > 2000 and dept.deptno = emp.deptno);
#exits和in对比 #in:先执行子查询,将子查询结果返回给主查询,主查询根据返回的结果后续处理。 #exits:先执行主查询,子查询根据主查询传输的数据,依次在子查询中匹配,如果能够找到与主查询相匹配的记录,则返回true,显示主查询的结果;如果不能匹配,则返回false,则主查询该记录不会显示在结果集中。 |
3.联合查询 union 去重、union all 不去重
select * from emp where deptno =20 union all select * from emp where sal >2000; |