子查询

2017-02-05  本文已影响0人  52Hz的蓝鲸

子查询所要解决的问题是不能一步求解,需要两步或者多步求解的类型

注意的问题:

1、括号

2、合理的书写风格

3、可以在主查询的where select having from后面放置子查询

4、不可以在group by后面放子查询

5、强调from后面的子查询

(重要)---查询员工信息:员工号  姓名  薪水

select * from ( select empno,ename,sal from emp );

---查询员工信息:员工号  姓名  薪水  年薪

select * from ( select empno,ename,sal,sal*12 annlsal from emp );

6、主查询和子查询可以不是同一张表;只要子查询返回的结果主查询可以使用即可

查询部门名称是sales的员工的信息

select  e.*  from emp where e.deptno= (select * from dept where dname='sales' )------------子查询

select  e.*  from emp e,dept d where e.deptno=d.deptno and d.dname='sales'----------------多表查询

理论上使用多表查询比子查询快

7、一般不在子查询中使用order by;但top-N分析问题中,必须对子查询排序

8、子查询(内查询)在主查询之前一次执行完成,子查询的结果被主查询使用(外查询):一般先执行子查询,再执行主查询;但相关子查询例外

9、子查询分为:单行子查询和多行子查询

单行子查询只能使用单行操作符 多行子查询只能使用多行操作符

多行子查询操作符:

in             等于列表中的任何一个

any          和子查询返回的任意一个值比较

select * from emp where sal > (select min(sal) from emp where deptno=30)

=select * from emp where sal > any (select sal from emp where deptno=30)

all            和子查询返回的所有值比较

select * from emp where sal > (select max(sal) from emp where deptno=30)

=select * from emp where sal > all(select sal from emp where deptno=30)

10、注意子查询的null

not in 子查询中不能有空值

上一篇 下一篇

猜你喜欢

热点阅读